2016-08-30 11 views
8

ben ES6 içinde bunu nasıl anlamaya çalışıyorum ... özelliklerini biri tarafından bir dizideki bir nesneyi bulunES6: .. <p></p> Ben nesnelerin bu dizi var

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

..ve kendi yatırım türleri (hisse senetleri, seçenekler, tasarruflar) her kişinin toplam değeri eklemek istediğiniz nesnelerin bu yeni dizi ..

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

ben döngü originalData içinden ve "geçerli her özellik kaydet Nesne "içinde bir ..

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) 
} 

cevap

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

Ve bütün kodu:

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 }