我在数组中有多个对象。它们每个都有分配给他们的labelId。如果标签ID相同,则需要通过将一些值放置在新组合对象的数组内来组合对象。
[
{
field: "legalName",
isOpened: false,
label: "Legal Name",
labelId: 1,
value: "John Doe"
},
{
field: "homeAddress1",
isOpened: false,
label: "Home Address",
labelId: 2,
value: "2343 Main Street"
},
{
field: "homeAddress2",
isOpened: false,
label: "Home Address",
labelId: 2,
value: "New York, NY"
}
]
我希望它看起来像什么
[
{
isOpened: false,
label: "Legal Name",
labelId: 1,
values:
[
{field: "legalName", value: "John Doe"}
]
},
{
isOpened: false,
label: "Home Address",
labelId: 2,
values:
[
{field: "homeAddress1", value: "2343 Main Street"},
{field: "homeAddress2", value: "New York, NY"}
]
}
]
我要从原始对象中删除字段和值,并将其放入所有对象的值数组中,无论它们是否具有相同的labelId。
到目前为止的代码-
personalInfoArray.forEach(info => {
personalInfoArray.forEach(info2 => {
if ((info.labelId === info2.labelId) && (info.field !== info2.field)) {
info.values = [
{field: info.field, value: info.value},
{field: info2.field, value: info2.value}
]
}
})
})
我要遍历同一数组两次,以确定对象是否具有相同的labelId(如果成功)-创建数组。问题是我没有删除属性,而另一个对象仍然存在。如果它们没有相同的labelId,则什么也不会发生。
谢谢
答案 0 :(得分:3)
这是一种使用功能Array.prototype.reduce
将对象按labelId
分组和使用功能函数Object.values
来提取分组对象的方法。
let arr = [{ field: "legalName", isOpened: false, label: "Legal Name", labelId: 1, value: "John Doe" }, { field: "homeAddress1", isOpened: false, label: "Home Address", labelId: 2, value: "2343 Main Street" }, { field: "homeAddress2", isOpened: false, label: "Home Address", labelId: 2, value: "New York, NY" }],
result = Object.values(arr.reduce((a, {labelId, field, isOpened, label, value}) => {
(a[labelId] || (a[labelId] = {isOpened, label, labelId, values: []})).values.push({field, value});
return a;
}, Object.create(null)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }