簡體   English   中英

用鍵將數組轉換為對象

[英]Convert array to object with key

我有一個對象

{
    ids: ['11', '12', '13', '14'],
    cat: 1
}

我想將其轉換為

[
    { id: '11', cat: 1 },
    { id: '12', cat: 1 },
    { id: '13', cat: 1 },
    { id: '14', cat: 1 }
]

是否可以執行這種單一語法? 我們可以為此使用擴展語法嗎?

好吧,這只是idsmap

 var obj = { ids: ['11', '12', '13', '14'], cat: 1 }; console.log(obj.ids.map((x) => { return { id: x, cat: obj.cat }; })); 

如果具有對象的數組再次調用getCartesian並構建新的對象,則可以采用遞歸函數,該函數將所有鍵/值對分開並通過迭代值來構建新的笛卡爾積。

鍵必須與結果集中的后續名稱相同。

 function getCartesian(object) { return Object.entries(object).reduce((r, [k, v]) => { var temp = []; r.forEach(s => (Array.isArray(v) ? v : [v]).forEach(w => (w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x => temp.push(Object.assign({}, s, { [k]: x })) ) ) ); return temp; }, [{}]); } var data = { id: ['11', '12', '13', '14'], cat: 1 }; console.log(getCartesian(data)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

var test = {
  ids: ['11', '12', '13', '14'],
  cat: 1
}

// one line
test.ids.map(i => { return {id: i, cat: test.cat} } )

暫無
暫無

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

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