简体   繁体   English

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

[英]Reduce nested array of objects to array of objects

I have an array like我有一个像

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

I have to display this nested array objects as flat key value list.我必须将此嵌套数组对象显示为平面键值列表。 So How to reduce this like below.那么如何减少这种情况,如下所示。

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"}
]

Using reducearray i will map with object keys and display as key value list in html.使用 reducearray 我将 map 与 object 键并显示为 html 中的键值列表。

Need to display as flat list using jsx like below需要使用 jsx 显示为平面列表,如下所示

Id: 1 Name: abc City: first ity Country: firstcountry City: second city Country: second country Id:2 Name: another name..... ...... .... ID:1 姓名:abc 城市:第一个国家 国家:第一个国家 城市:第二个城市 国家:第二个国家 ID:2 姓名:另一个名字............

Can anyone help me on this plz.. is it possible with reduce only?任何人都可以帮我解决这个问题。. 仅减少可能吗?

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)

You could take a flat map with the destructured rest object and Address array.您可以使用带有解构 rest object 和Address数组的平面 map。

 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; }

Solution with 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM