简体   繁体   中英

How to extract the property values of a object into an array and make elements in the array different?

i got this array

var data = [
    {F: 'a', T: 'z', V:1},
    {F: 'b', T: 'z', V:2},
    {F: 'c', T: 'z', V:3}
]

and i want got this array below I used method forEach

 var nodes = [];
 data.forEach(function(element) {
   nodes.push({name:element.F})
   nodes.push({name:element.T}            
 })

but got a repetitive element{name:'z'} in array but don't want the repetitive element ,I want the array below

[
    {name:'a'},
    {name:'b'},
    {name:'c'},
    {name:'z'},
]

You can first create new Set and then add values of F and T and then transform that set to array and use map() .

 var data = [{F: 'a', T: 'z', V:1},{F: 'b', T: 'z', V:2},{F: 'c', T: 'z', V:3}] var set = new Set() data.forEach(function(e) { if(eF) set.add(eF) if(eT) set.add(eT) }) var result = [...set].map(e => ({name: e})) console.log(result) 

You could use a hash table and push only values which are not in the hash table.

 var data = [{ F: 'a', T: 'z', V: 1 }, { F: 'b', T: 'z', V: 2 }, { F: 'c', T: 'z', V: 3 }], nodes = [], hash = Object.create(null); data.forEach(function(element) { ['F', 'T'].forEach(function (k) { hash[element[k]] || nodes.push({ name: element[k] }); hash[element[k]] = true; }); }); nodes.sort(function (a, b) { return a.name.localeCompare(b.name); }); console.log(nodes); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The solution using Array.prototype.reduce() and Array.prototype.indexOf() functions:

 var data = [{F: 'a', T: 'z', V:1}, {F: 'b', T: 'z', V:2}, {F: 'c', T: 'z', V:3}], result = data.reduce(function (a, o) { // getting an array of unique values if (a.indexOf(oF) === -1) a.push(oF); if (a.indexOf(oT) === -1) a.push(oT); return a; }, []) .map(function (v) { return {name: v}; }); console.log(result); 

Or using unique key object capability (only if initial your object value (here data) are stringable) (no if in the code) :

 var data = [{ F: 'a', T: 'z', V: 1 }, { F: 'b', T: 'z', V: 2 }, { F: 'c', T: 'z', V: 3 }]; var result = Object.keys( data.reduce( (memo, el) => { memo[el.F] = undefined; memo[el.T] = undefined; return memo; }, {}) ).reduce( (memo, el) => { memo.push({name: el}); return memo; }, []); console.log(result) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM