javascript - 如何在 JS 中对数组进行非规范化
问题描述
我有以下形式的数据集
let data = [
{
"id": {
"primary": "A1"
},
"msg": 1
}, {
"id": {
"primary": "A1"
},
"msg": 2
}, {
"id": {
"primary": "B2"
},
"msg": 3
}
]
我想将其转换为
newData = [
{
"id": {
"primary": "A1"
},
"items": [
{ "msg": 1 },
{ "msg": 2 }
]
},
{
"id": {
"primary": "B2"
},
"items": [
{ "msg": 3 }
]
}
]
我认为该方法类似于以下内容,但不确定undefined
在这种情况下如何检查值。
let newData = [];
for (let i = 0; i < data.length; i++) {
if (newData[i]['id']['primary'] === data[i]['id']) newData.push(data[i]['id'])
else newData[i]['items'].push(data[i]['msg'])
}
如何转换原始数据集以合并具有匹配项的条目primary id
?
解决方案
一种选择是使用.reduce()
从现有数组创建一个新数组。
我添加了评论以澄清。
let data = [ { "id": { "primary": "A1" }, "msg": 1 }, { "id": { "primary": "A1" }, "msg": 2 }, { "id": { "primary": "B2" }, "msg": 3 } ];
let result = data.reduce((out,item) => {
let {id, ...items} = item; //Separate the "id" and "everything else"
let existing = out.find(({id}) => id.primary == item.id.primary);
existing //have we seen this ID already?
? existing.items.push(items) //yes - add the items to it
: out.push({ id: {...id}, items: [items]}); //no - create it
return out;
}, []);
console.log(result);
几点注意事项:
您可能会注意到我已经使用 设置了 ID
id: {...id}
,尽管它id
已经是一个对象。这是因为使用现有id
对象会创建一个引用,而{...id}
创建一个浅拷贝。我没有在
msg
任何地方指定该属性。相反,任何未添加的属性都id
将添加到items
列表中(示例如下)。let data = [ { "id": { "primary": "A1" }, "msg": 1, "otherStuff": "Hello World!" }, { "id": { "primary": "A1" }, "msg": 2, "AnotherThing": true }, { "id": { "primary": "B2" }, "msg": 3, "someOtherProperty": false } ]; let result = data.reduce((out,item) => { let {id, ...items} = item; let existing = out.find(({id}) => id.primary == item.id.primary); existing ? existing.items.push(items) : out.push({ id: {...id}, items: [items]}); return out; }, []); console.log(result);
也就是说,如果您开始嵌套对象(ID 除外),它们可能会被包含为引用;
...items
只是一个浅拷贝。如果是这种情况,请考虑像
JSON.parse(JSON.stringify(...))
深拷贝这样的东西。请务必阅读链接;有一些警告。
推荐阅读
- python - TimeDistributed layer
- typescript - 打字稿:为什么 PromiseLike 在异步函数的对象中可能是 this 的类型?
- python - 改变类外的类属性值
- python - 类的澄清
- javascript - 使用 fetch 时如何访问 JSON?
- java - 使用低级 Kafka Stream API 执行 context.forward() 时的 NPE
- django - Django 组经理获取每个成员角色
- angular - 组件之间通信中的数据重复
- ruby - 使用 object.get 时内存使用效率低下
- javascript - js:迭代嵌套对象的更好方法?