簡體   English   中英

對象數組到屬性值的對象

[英]Array of objects to object of property values

我有此數據:

[
    {foo: 1, bar: a},
    {foo: 2, bar: b},
    {foo: 3, bar: c},
]

將數據轉換為類似內容的最簡單方法是什么

{
    customLabel1 : [1,2,3],
    customLabel2 : [a,b,c]
}

我想出了這個

{
    customLabel1: data.map((a) => {return a.foo} ),
    customLabel2: data.map((a) => {return a.bar} )
}

有沒有更簡單的方法或更快的方法?

如果您想更簡單,則您的代碼已經使用胖箭頭語法非常接近了。 您可以刪除括號和return關鍵字:

{
    customLabel1: data.map(a => a.foo),
    customLabel2: data.map(a => a.bar)
}

如果您想要更快,我認為您必須犧牲一些簡單性。 撰寫本文時,您要遍歷兩次data 如果您迭代一次,它將看起來像這樣:

 var data = [ {foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 3, bar: 'c'}, ]; var o = {customLabel1: [], customLabel2: []}; data.forEach(a => { o.customLabel1.push(a.foo); o.customLabel2.push(a.bar); }); console.log(o); 

map調用的較短語法可以是:

data.map(el => el.prop);

話雖如此,我將為此定義一個輔助函數:

function pluck(arr, props) {
   return Object.keys(props).reduce((ret, prop) => {
     ret[prop] = arr.map(el => el[props[prop]]);
     return ret;
   }, {});
} 

var ret = pluck(data, {
  customLabel1: 'foo',
  customLabel2: 'bar'
});

如果您不知道按鍵,可以使用此表格

{
    customLabel1: data.map(function(element) { return element[Object.keys(element)[0]];}),
    customLabel2: data.map(function(element) { return element[Object.keys(element)[1]];})
}

您可以將一個對象用於鍵映射,然后進行迭代。

 var data = [{ foo: 1, bar: 'a' }, { foo: 2, bar: 'b' }, { foo: 3, bar: 'c' }], labels = { customLabel1: 'foo', customLabel2: 'bar' }, result = {}; data.forEach(a => Object.keys(labels).forEach(k => { result[k] = result[k] || []; result[k].push(a[labels[k]]); })); console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM