Подтвердить что ты не робот

ES6: поиск объекта в массиве одним из его свойств

Я пытаюсь выяснить, как это сделать в 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 (currinvestment) value (currvalue) 
}
4b9b3361

Ответ 1

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 }

Ответ 2

Я хотел бы использовать некоторые производные этого:

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