[英]Transform nested array of objects to an object
我正在嘗試將嵌套數組轉換為對象,我進行了多次嘗試但沒有成功。
這些是我擁有的數據
[
['key1', { childKey1: "text" }, { childKey2: "text" }],
['key2', { childKey1: "text" }, { childKey2: "text" }]
]
這是我需要的數據
{
key1: {
childKey1: "text",
childKey2: "text"
},
key2: {
childKey1: "text",
childKey2: "text"
}
}
將數據映射到條目 - [[key, value], [key, value]]。 使用解構來獲取鍵(子數組中的第一項),並使用剩余語法來獲取對象數組。 通過將對象數組擴展到Object.assign()
以獲取值來合並對象數組。 使用Object.fromEntries()
將條目轉換為對象。
const data = [['key1', {childKey1: "text"}, {childKey2: "text"}], ['key2', {childKey1: "text"}, {childKey2: "text"}]] const result = Object.fromEntries(data.map( ([k, ...v]) => [k, Object.assign({}, ...v)] )) console.log(result)
.reduce()方法是解決這個問題的另一種方法。
const arr = [['key1', {childKey1: "text"}, {childKey2: "text"}], ['key2', {childKey1: "text"}, {childKey2: "text"}]]; const newArr = arr.reduce((accumulator, currVal) => { const [key, ...values] = currVal; // destruct array and separate key from all other values accumulator[key] = Object.assign({}, ...values); // assign values to your final object, using the key extracted above return accumulator; }, {}); console.log(newArr);
你可以嘗試 reduce 來完成這樣的任務。 你可以這樣做:
const data = [ ["key1", { childKey1: "text" }, { childKey2: "text" }], ["key2", { childKey1: "text" }, { childKey2: "text" }] ]; function dataToJSON(data) { return data.reduce((acc, current) => { const [key, ...values] = current; acc[key] = Object.assign({}, ...values); return acc; }, {}); } console.log(dataToJSON(data));
適用於任何數量的兒童。 你必須小心重復的鍵不要覆蓋以前的鍵。
我知道這已經得到了回答,但這是我的嘗試:
let jsonArray = [['key1', {childKey1: "text"}, {childKey2: "text"}], ['key2', {childKey1: "text"}, {childKey2: "text"}]]; let newJson = {}; for(var i=0; i<jsonArray.length; i++){ newJson[jsonArray[i][0]] = Object.assign({}, ...jsonArray[i].slice(1)); } console.log(newJson);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.