将带有object的数组转换为带有2个对象的数组

时间:2018-04-23 13:18:36

标签: javascript arrays javascript-objects

当我在菜单中选择Fruit(例如“apple”)时,我想创建一个新的数组(myArrayFruitSelect)。

MyArray [{ fruit: "Apple", value1: 89, value2: 2.6 },{ fruit: "Banana", value1: 59, value2: 3.6 },{ fruit: "Orange", value1: 49, value2: 5.6 }...etc]

var selectFruit = document.getElementById('FiltreFruits').value;

var myArrayFruitSelect = _(_.where(rows,  { fruit: selectFruit}));

我想得到这样的结果:

myArrayFruitSelect[{ fruit: "Apple", value1: 89},{ fruit: "Apple", value2: 2.6}]

1 个答案:

答案 0 :(得分:0)

您可以使用ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap(); exeConfigurationFileMap.ExeConfigFilename = "your file path here"; Configuration customConfig = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None); 方法,为reduce()值等于value值的每个fruit属性添加新对象。

selectFruit
const array =  [{ fruit: "Apple", value1: 89, value2: 2.6 },{ fruit: "Banana", value1: 59, value2: 3.6 },{ fruit: "Orange", value1: 49, value2: 5.6 }]

var selectFruit = document.getElementById('FiltreFruits').value;
const result = array.reduce((r, {fruit, value1, value2}) => {
  if(fruit == selectFruit) r.push({fruit, value1}, {fruit, value2})
  return r;
}, [])
console.log(result)

如果您想要没有硬编码密钥的更动态解决方案,可以在<input type="text" value="Apple" id="FiltreFruits">内使用forEach循环。

reduce
const array =  [{ fruit: "Apple", value1: 89, value2: 2.6 },{ fruit: "Banana", value1: 59, value2: 3.6 },{ fruit: "Orange", value1: 49, value2: 5.6 }]

var selectFruit = document.getElementById('FiltreFruits').value;
const result = array.reduce((r, {fruit, ...rest}) => {
  if(fruit == selectFruit) Object.keys(rest).forEach(key => r.push({fruit, [key]: rest[key]}))
  return r;
}, [])
console.log(result)