我有一个包含产品名称及其存储的数组
let array = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storage: "256GB"}, {name: "samsung A", storage: "256GB"}]
我有另一个数组,其中包含需要存储的所有名称,让数组为
let array1 = ["samsung A", "samsung B", "samsung C"]
比较上面的两个数组,我想映射每个键的可用存储空间。
我已经尝试过
array.filter(el => el.name === "samsung A").map(item => item.storage)
但是在上面我手动给出了“samsung A”,但我想从 array2 中的所有可用键中获取数组中可用的所有存储
let data = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storage: "256GB"}, {name: "samsung A", storage: "256GB"}]
let phones = ["samsung A", "samsung B", "samsung C"]
let result = [];
// Loop all phones
phones.forEach(phone => {
// Get all data by name
let filteredData = data.filter(d => d.name === phone)
// Map all storages
let storages = filteredData.map(fd => fd.storage)
// Create result
let entry = {name: phone, storages: storages}
result.push(entry)
})
console.log(result)