[英]How to extract array elements that are values of an associative array (object) one by one
[英]How to extract the property values of a object into an array and make elements in the array different?
我有这个阵列
var data = [
{F: 'a', T: 'z', V:1},
{F: 'b', T: 'z', V:2},
{F: 'c', T: 'z', V:3}
]
我想在下面使用这个数组我使用方法forEach
var nodes = [];
data.forEach(function(element) {
nodes.push({name:element.F})
nodes.push({name:element.T}
})
但是在数组中得到了一个重复的元素{name:'z'}但是不想要重复的元素,我想要下面的数组
[
{name:'a'},
{name:'b'},
{name:'c'},
{name:'z'},
]
您可以先创建新的Set
,然后添加F
和T
值,然后将该集转换为数组并使用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)
您可以使用哈希表并仅推送不在哈希表中的值。
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; }
使用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);
或者使用唯一的密钥对象功能(仅当初始对象值(此处为数据)是可字符串的时)(如果在代码中,则为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.