[英]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.