2016-08-30 5 views
8

मैं कैसे 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 के माध्यम से और "वर्तमान में से प्रत्येक संपत्ति को बचाने वस्तु "एक चलो ..

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

उत्तर

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

संबंधित मुद्दे