簡體   English   中英

獲取在 Object 中找到的所有屬性

[英]Get all properties found in Object

我有一個對象數組

const data = [{id:1, a:false, b:[5,4]},
 {id:2, a:true, b:[]},
 {id:3, c:'', d:{}},
 {id:4, e:[1,2,3], f:{h: 1}}];

基本上我想返回一個 object,它具有 object 中的所有屬性,然后給我最新的值。

所以它應該給我以下結果:

// { id: 4, a: false, b: [], c: '', d: {}, e: [1,2,3], f: {h: 1}}

我玩過 Object.getOwnPropertyNames 和 Object.values ,但現在卡住了一段時間,對 JS 來說還很新。

您可以使用對Object.assign的簡單調用將data內的所有對象合並到單個 object。

Object.assign({}, ...data)

該方法可以采用任意數量的源對象進行合並。 因此, 展開數組以將它們作為參數傳遞。 由於對象是按順序合並的,所以后面的對象是首選的。 如果一個屬性存在於多個對象中,則索引較高的 object 會覆蓋之前的值。 所以, id:4出現在 output

這是一個片段:

 const data = [{id:1, a:false, b:[5,4]}, {id:2, a:true, b:[]}, {id:3, c:'', d:{}}, {id:4, e:[1,2,3], f:{h: 1}}]; const output = Object.assign({}, ...data) console.log(output)

我會像這樣使用 Array.forEach() 和 Object.assign() :

const arr = [{id:1, a:true, b:[]},
 {id:2, a:false, b:[]},
 {id:3, foo:'', bar:{}},
 {id:4, bla:[1,2,3], blabla:{x: 1}}];

const obj = {};
arr.forEach(el => Object.assign(obj, el));


console.log(obj);

forEach() 遍歷數組中的每個元素,並且 Object.assign 將 el 的屬性應用於現有的 Object obj。 在每次迭代中,它將創建 obj 中不存在的屬性或重新分配確實存在的屬性的值。

const data = [{id:1, a:true, b:[]},
              {id:2, a:false, b:[]},
              {id:3, foo:'', bar:{}},
              {id:4, bla:[1,2,3], blabla:{x: 1}}];
let result = {};
    data.map((item) => {
        result = {...result, ...item};
    }
)
console.log(result);

暫無
暫無

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

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