英文:
Convert object and its sub-object in an array into map
问题
我有一个类似这样的对象数组:
let array = [
{
"A": [
{
"X": "abc123",
"Y": "abc213",
"Z": "xyz123"
},
{
"X": "xyz7",
"Y": "wqr",
"Z": "dasd"
}
]
},
{
"B": [
{
"X": "sadasd",
"Y": "asdasd",
"Z": "sadasd"
},
{
"X": "ffff531",
"Y": "asdddz",
"Z": "xx11155"
}
]
}
]
我想要将其转换为这样的映射,外部键仍然是A/B,但内部键应该是X的值,指向对象本身。
{
"A": {
"abc123": {
"X": "abc123",
"Y": "abc213",
"Z": "xyz123"
},
"xyz7": {
"X": "xyz7",
"Y": "wqr",
"Z": "dasd"
}
},
"B": {
"sadasd": {
"X": "sadasd",
"Y": "asdasd",
"Z": "sadasd"
},
"ffff531": {
"X": "ffff531",
"Y": "asdddz",
"Z": "xx11155"
}
}
}
我尝试使用reduce方法,但只能在没有嵌套对象时将其转换为映射,而不能处理嵌套对象。如何做到这一点?是否可以使用Array.prototype.reduce方法?
【翻译完毕】
英文:
I have an array of objects like this:
let array = [
{
"A": [
{
"X": "abc123",
"Y": "abc213",
"Z": "xyz123"
},
{
"X": "xyz7",
"Y": "wqr",
"Z": "dasd"
}
]
},
{
"B": [
{
"X": "sadasd",
"Y": "asdasd",
"Z": "sadasd"
},
{
"X": "ffff531",
"Y": "asdddz",
"Z": "xx11155"
}
]
}
]
And I want to convert into map such that The outer key would be A/B as it is but the inner key should be the value of X pointing towards the value as the object itself.
{
"A": {
"abc123":{
"X": "abc123",
"Y": "abc213",
"Z": "xyz123"
},
"xyz7": {
"X": "xyz7",
"Y": "wqr",
"Z": "dasd"
}
},
"B": {
"sadasd":{
"X": "sadasd",
"Y": "asdasd",
"Z": "sadasd"
},
"ffff531":{
"X": "ffff531",
"Y": "asdddz",
"Z": "xx11155"
}
}
}
I tried using the reduce method but I was only able to covert this to map when there are no nested objects but not with nested objects.
How can I do this ? Is this possible using Array.prototype.reduce
method?
答案1
得分: 2
你可以构建一个单一对象,并创建具有所需键的嵌套对象。
const data = [{ A: [{ X: "abc123", Y: "abc213", Z: "xyz123" }, { X: "xyz7", Y: "wqr", Z: "dasd" }] }, { B: [{ X: "sadasd", Y: "asdasd", Z: "sadasd" }, { X: "ffff531", Y: "asdddz", Z: "xx11155" }] }];
const result = Object.fromEntries(Object.entries(Object.assign({}, ...data)).map(([k, v]) => [k, Object.fromEntries(v.map(o => [o.X, o]))]));
console.log(result);
英文:
You could build a single object and create nested object with wanted key.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
data = [{ A: [{ X: "abc123", Y: "abc213", Z: "xyz123" }, { X: "xyz7", Y: "wqr", Z: "dasd" }] }, { B: [{ X: "sadasd", Y: "asdasd", Z: "sadasd" }, { X: "ffff531", Y: "asdddz", Z: "xx11155" }] }],
result = Object.fromEntries(Object
.entries(Object.assign({}, ...data))
.map(([k, v]) => [k, Object.fromEntries(v.map(o => [o.X, o]))]));
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论