Javascript ES6:通过数组中的一个属性查找对象
我想知道如何在ES6中做到这一点 我有这个对象数组Javascript ES6:通过数组中的一个属性查找对象,javascript,arrays,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":
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"}
];
…这个新的对象数组,我想在其中添加每个人的投资类型(股票、期权、储蓄)的总价值
我循环使用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)
}
而整个代码:
const originalData=[
{“投资者”:“休”,“价值”:5,“投资”:“股票”},
{“投资者”:“Rob”,“价值”:15,“投资”:“期权”},
{“投资者”:“苏”,“价值”:25,“投资”:“储蓄”},
{“投资者”:“抢劫”,“价值”:15,“投资”:“储蓄”},
{“投资者”:“休”,“价值”:2,“投资”:“股票”},
{“投资者”:“Liz”,“价值”:85,“投资”:“期权”},
{“投资者”:“Liz”,“价值”:16,“投资”:“期权”},
];
常数newData=[
{“投资者”:“休”,“股票”:0,“期权”:0,“储蓄”:0},
{“投资者”:“抢劫”,“股票”:0,“期权”:0,“储蓄”:0},
{“投资者”:“Liz”,“股票”:0,“期权”:0,“储蓄”:0},
];
对于(原始数据的{投资者、价值、投资}){
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 );
};
newData.find(x => x.investor === investor)
var arrayFindObjectByProp = (arr, prop, val) => {
return arr.find( obj => obj[prop] == val );
};