2016-08-30 8 views
8

Próbuję dowiedzieć się, jak to zrobić w ES6 ...ES6: Znajdź obiekt w tablicy przez jednego ze swoich właściwości

mam ten tablicę obiektów ..

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"} 
]; 

..i ta nowa tablica obiektów gdzie chcę dodać każdej osoby łączna wartość ich typów inwestycji (akcje, opcje, oszczędności) ..

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} 
]; 

i pętli originalData i zapisać każda właściwość „prąd obiekt "w 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) 
} 

Odpowiedz

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

I cały kod:

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 }

Powiązane problemy