[英]How can I find objects with same keys values in array?
I have an array of objects that looks like this:我有一个看起来像这样的对象数组:
const arr = [
{ type: 'type', fields: ['field1'] },
{ type: 'type2' },
{ type: 'type', fields: ['field2'] },
]
And I need to find objects with the same type to merge fields key in them, like this:我需要找到具有相同类型的对象来合并其中的字段键,如下所示:
const arr = [
{ type: 'type', fields: ['field1', 'field2'] },
{ type: 'type2' },
{ type: 'type', fields: ['field1', 'field2'] },
]
My plan was to filter through the array, but my problem is that I don't know which type will send me API, so filtering by item.type
wouldn't work for me.我的计划是过滤数组,但我的问题是我不知道哪种类型会发送给我 API,所以按item.type
过滤对我不起作用。
If that is the exact solution that you want.如果那是您想要的确切解决方案。 Following code snippet may help you.以下代码段可能会对您有所帮助。
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);
This will print这将打印
[
{ type: 'type', fields: ['field1', 'field2'] },
{ type: 'type2' },
{ type: 'type', fields: ['field1', 'field2'] },
]
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"]} //]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.