ES6:通过其中一个属性在数组中查找对象

时间:2016-08-30 19:10:09

标签: javascript arrays

我正试图弄清楚如何在ES6中做到这一点......

我有这个对象数组..

const originalData=[
{"investor": "Sue", "value": 5, "investment": "stocks"},
{"investor": "Rob", "value": 15, "investment": "options"},
{"investor": "Sue", "value": 25, "investment": "savings"},
{"investor": "Rob", "value": 15, "investment": "savings"},
{"investor": "Sue", "value": 2, "investment": "stocks"},
{"investor": "Liz", "value": 85, "investment": "options"},
{"investor": "Liz", "value": 16, "investment": "options"}
];

..和这个新的对象数组,我想在其中添加每个人的投资类型(股票,期权,储蓄)的总价值。

const newData = [
{"investor":"Sue", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Rob", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Liz", "stocks": 0, "options": 0, "savings": 0}
];

我循环遍历originalData并在let ..

中保存“当前对象”的每个属性
for (let obj of originalData) {
   let currinvestor = obj.investor;
   let currinvestment = obj.investment;
   let currvalue = obj.value;

   ..but here I want to find the obect in newData that has the property = currinvestor (for the "investor" key)
   ...then add that investment type's (currinvestment) value (currvalue) 
}

2 个答案:

答案 0 :(得分:51)

newData.find(x => x.investor === investor)

整个代码:



const originalData = [
  { "investor": "Sue",   "value":  5,   "investment": "stocks"  },
  { "investor": "Rob",   "value": 15,   "investment": "options" },
  { "investor": "Sue",   "value": 25,   "investment": "savings" },
  { "investor": "Rob",   "value": 15,   "investment": "savings" },
  { "investor": "Sue",   "value":  2,   "investment": "stocks"  },
  { "investor": "Liz",   "value": 85,   "investment": "options" },
  { "investor": "Liz",   "value": 16,   "investment": "options" },
];

const newData = [
  { "investor": "Sue",   "stocks": 0,   "options": 0,   "savings": 0 },
  { "investor": "Rob",   "stocks": 0,   "options": 0,   "savings": 0 },
  { "investor": "Liz",   "stocks": 0,   "options": 0,   "savings": 0 },
];

for (let {investor, value, investment} of originalData) {
  newData.find(x => x.investor === investor)[investment] += value;
}

console.log(newData);

.as-console-wrapper.as-console-wrapper { max-height: 100vh }




答案 1 :(得分:0)

我会使用它的一些衍生形式:

    var arrayFindObjectByProp = (arr, prop, val) => {
        return arr.find( obj => obj[prop] == val );
    };