简体   繁体   中英

How can I iterate over an array?

I have this JSON structure:

const arr = [
        {
          id: "TaskStatuses",
          rows: [
            {id: "1", name: "Success"},
            {id: "2", name: "Error"},
          ]
        },
        {
          id: "Objects",
          rows: [
            {id: "1", name: "Object1"},
            {id: "2", name: "Object2"},
          ]
        },
        {
          id: "Groups",
          rows: [
            {id: "1", name: "Group1"},
            {id: "2", name: "Group2"},
          ]
        },
      ]

I need to create array with some condition. If my condition correctly I will push elements arr.rows.

Finally i want to get this structure:

[
{
  Objects: "Object1",
  Groups: "Group1"
},
  {
    Objects: "Object2",
    Groups: "Group2"
  }
]

I try to do like this

let sites = []
    for (let el in arr) {
            if (arr.id == "Objects") {
              for (let item of el.rows) {
                sites.push({Objects: item.name})
              }
            }
            if (arr.id == "Groups") {
              for (let item of el.rows) {
                sites.Groups = item.name
              }
            }
          }

You could map the wanted properties in new objects.

 const data = [{ id: "TaskStatuses", rows: [{ id: "1", name: "Success" }, { id: "2", name: "Error" }] }, { id: "Objects", rows: [{ id: "1", name: "Object1" }, { id: "2", name: "Object2" }] }, { id: "Groups", rows: [{ id: "1", name: "Group1" }, { id: "2", name: "Group2" }] }], ids = ['Objects', 'Groups'], result = data.reduce((r, { id, rows }) => ids.includes(id)? rows.map(({ name }, i) => ({...r[i], [id]: name })): r, [] ); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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