我有以下JSON数组对象:
const arrayExample = [
{
key: 5,
children:[
{
key: 51,
title: 'Create User'
},
{
key: 52,
title: 'Edit User'
}
]
},{
key: 2,
children:[
{
key: 21,
title: 'Create Email'
},
{
key: 22,
title: 'Edit Email'
}
]
}
];
每个数组都包含一个键,
如何在儿童的数组键中使用JavaScript map()函数并获得如下响应?:
const expectedResult = [
{key:5, children: [51,52]},
{key:2, children: [21,22]}
];
答案 0 :(得分:-1)
您可以使用嵌套的map()
const arr = [
{
key: 5,
children:[
{
key: 51,
title: 'Create User'
},
{
key: 52,
title: 'Edit User'
}
]
},{
key: 2,
children:[
{
key: 21,
title: 'Create Email'
},
{
key: 22,
title: 'Edit Email'
}
]
}
];
let result = arr.map(x => (({...x,children:x.children.map(a => a.key)})))
console.log(result);
答案 1 :(得分:-1)
const expectedResult = arrayExample.map((item) => {
const keyOnlyArray = [];
item.children.map((children) => {
keyOnlyArray.push(children.key)
})
return {
key : item.key,
children : keyOnlyArray
}
})
答案 2 :(得分:-2)
一种方法是两次使用map
,一次是在每个对象内部创建children
数组,一次是使用keys
键和children
< / p>
const arrayExample = [{
key: 5,
children: [{
key: 51,
title: 'Create User'
},
{
key: 52,
title: 'Edit User'
}
]
}, {
key: 2,
children: [{
key: 21,
title: 'Create Email'
},
{
key: 22,
title: 'Edit Email'
}
]
}];
let expectedResult = arrayExample.map(function(item) {
return {
key: item.key,
// children is an array , so again using map to get an array of key's value
children: item.children.map(function(childKey) {
return childKey.key
})
}
});
console.log(expectedResult)