将嵌套的对象数组减少为对象数组

Reduce nested array of objects to array of objects

我有一个像

这样的数组
Const array=[
{
id:1,
name:"abc",
Address:[
   {
    City: "something",
    Country: "first country"
   },
   {
    City: "other city",
    Country: "country"
    }
  ]
},
{
...........
}
];

我必须将此嵌套数组对象显示为平面键值列表。那么如何像下面这样减少它。

Reducedarray = [
  { Id: 1, name: "abc" },
  { City: "something", country: "first country"},
  { City: "other city", country: "country"},
  { Id: 2, name: "bbc" },
  { City: "bbcsomething", country: "fbbct country"},
  { City: "other city", country: "country"}
]

使用 reducearray 我将映射对象键并在 html 中显示为键值列表。

需要像下面这样使用 jsx 显示为平面列表

编号:1 姓名:abc 城市:第一城市 国家:第一国 城市:二线城市 国家:第二国 Id:2 名字:另一个名字 ..... …… ....

任何人都可以帮我解决这个问题吗..是否可以只使用 reduce?

const array= [
{
id:1,
name:"abc",
Address:[
   {
    City: "something",
    Country: "first country"
   },
   {
    City: "other city",
    Country: "country"
    }
  ]
},
];

const array2 = []

for(let el of array) {
  
    if(el.id) array2.push({id: el.id, name: el.name})
    
    if(el.Address) {
        
        for(let element of el.Address) {
          
          array2.push({ city: element.City, country: element.Country})
        }
    }
  
  
}

console.log(array2)

您可以使用解构的剩余对象和 Address 数组制作平面图。

const
    array = [{ id: 1, name: "abc", Address: [{ City: "something", Country: "first country" }, { City: "other city", Country: "country" }] }],
    result = array.flatMap(({ Address, ...o }) => [o, ...Address]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

reduce 解决方案:

const data = [{ id: 1, name: "abc", Address: [{ City: "something", Country: "first country" }, { City: "other city", Country: "country" }] }, { id: 2, name: "dfe", Address: [{ City: "something1", Country: "second country" }, { City: "city", Country: "new country" }] }];

const Reducedarray = data.reduce((acc, { Address, ...rest }) => (
  [...acc, rest, ...Address]
), []);

console.log(Reducedarray );
.as-console-wrapper { max-height: 100% !important; top: 0; }