简体   繁体   English

如何将对象的属性值提取到数组中并使数组中的元素不同?

[英]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 我想在下面使用这个数组我使用方法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:'z'}但是不想要重复的元素,我想要下面的数组

[
    {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() . 您可以先创建新的Set ,然后添加FT值,然后将该集转换为数组并使用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: 使用Array.prototype.reduce()Array.prototype.indexOf()函数的解决方案:

 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) : 或者使用唯一的密钥对象功能(仅当初始对象值(此处为数据)是可字符串的时)(如果在代码中,则为no):

 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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