我有一個看起來像這樣的物件陣列:
const arr = [
{ type: 'type', fields: ['field1'] },
{ type: 'type2' },
{ type: 'type', fields: ['field2'] },
]
我需要找到具有相同型別的物件來合并其中的欄位鍵,如下所示:
const arr = [
{ type: 'type', fields: ['field1', 'field2'] },
{ type: 'type2' },
{ type: 'type', fields: ['field1', 'field2'] },
]
我的計劃是過濾陣列,但我的問題是我不知道哪種型別會向我發送 API,因此過濾 byitem.type對我不起作用。
uj5u.com熱心網友回復:
如果那是您想要的確切解決方案。以下代碼片段可能對您有所幫助。
const arr = [
{ type: 'type', fields: ['field1']},
{ type: 'type2'},
{ type: 'type', fields: ['field2']}
]
const modifyArr = (data) => {
let res = [];
arr.map((item) => {
if(item.type == data.type){
if(Object.keys(item).includes('fields')){
res = res.concat(item.fields);
}
}
});
return Object.keys(data).includes('fields') ? { type: data.type, fields: res } : { type: data.type };
}
let newArr = arr.map(item => modifyArr(item));
console.log(newArr);
這將列印
[
{ type: 'type', fields: ['field1', 'field2'] },
{ type: 'type2' },
{ type: 'type', fields: ['field1', 'field2'] },
]
uj5u.com熱心網友回復:
const arr = [{ type: 'type', fields: ['field1']}, { type: 'type2'}, { type: 'type', fields: ['field2']}];
result = arr.map(({ type }) => {
const fields = arr.filter((o) => o.type === type).flatMap((e) => e.fields);
return { type, ...fields[0] ? { fields } : {} };
});
console.log(result);
//[
// {"type": "type", "fields": ["field1", "field2"]},
// {"type": "type2"},
// {"type": "type", "fields": ["field1", "field2"]}
//]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/376521.html
標籤:javascript 数组 目的
上一篇:什么時候參考鑄造切片物件?
