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

ES6: Find an object in an array by one of its properties

本文关键字:一个 属性 对象 查找 数组 ES6      更新时间:2023-09-26

我正试图弄清楚如何在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) 
}
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 }

我会使用这个的一些导数:

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