如何根据其他键从数组中过滤特定键值

问题描述 投票:0回答:1

我有一个包含产品名称及其存储的数组

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 中的所有可用键中获取数组中可用的所有存储

javascript reactjs arrays angularjs filter
1个回答
0
投票

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)

© www.soinside.com 2019 - 2024. All rights reserved.