gpt4 book ai didi

Javascript 对象展平为数组

转载 作者:行者123 更新时间:2023-11-28 14:13:12 25 4
gpt4 key购买 nike

我今天一直在尝试展平对象数组。我无法实现我所需要的,我需要访问最内部的元素(第 1 个)到最外部的元素(第 4 个),这里是数据示例,其中有一些空值可能会使其变得复杂:

   {
"School":"Arsenal 2011", //4th Element in new array
"Group":{
"Name":"Previous", //3rd Element in new array
"ParentGroup":{
"Name":"Arsenal", //2nd Element in new array
"ParentGroup":{
"Name":"USA", //1st Element in new array
"ParentGroup":null
}
}
},
"GroupDisplayText":null,
"Publisher":"Abbot",
"PublishedDate":"2011",
"PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
},
{
"School":"New York 2000",
"Group":{
"Name":"New York",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
},
"GroupDisplayText":null,
"Publisher":"DoE",
"PublishedDate":"2000",
"PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
}

我想要的输出数组是:

array[0] = { "美国","阿森纳","上一个"}array[x] = 所有其他数据

我如何在 JavaScript 中执行此操作?

如果有帮助的话我添加了一个plunker

https://plnkr.co/edit/LNlHArCob4Bix8VYHFwI?p=preview

谢谢

最佳答案

使用Array.prototype.map_.get()处理null场景

const data = [{
"School":"Arsenal 2011", //4th Element in new array
"Group":{
"Name":"Previous", //3rd Element in new array
"ParentGroup":{
"Name":"Arsenal", //2nd Element in new array
"ParentGroup":{
"Name":"USA", //1st Element in new array
"ParentGroup":null
}
}
},
"GroupDisplayText":null,
"Publisher":"Abbot",
"PublishedDate":"2011",
"PublishersWebsite":"http://google.com/USA/ADW%202011/Arsenal%202011.pdf"
},
{
"School":"New York 2000",
"Group":{
"Name":"New York",
"ParentGroup":{
"Name":"USA",
"ParentGroup":null
}
},
"GroupDisplayText":null,
"Publisher":"DoE",
"PublishedDate":"2000",
"PublishersWebsite":"http://google.com/USA/New York%202000%20Tables.pdf"
}];

const formatted = data.map(item => {
return [
_.get(item, 'Group.ParentGroup.ParentGroup.Name'),
_.get(item, 'Group.ParentGroup.Name'),
_.get(item, 'Group.Name'),
_.get(item, 'School')
];
});

console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>

关于Javascript 对象展平为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com