简体   繁体   中英

I have an array that I need to transform in a object (JAVASCRIPT)

Well, basically I have an array that has an objects with names and this objects has an array of objects inside, looks likes this:

var array = [
  {articles: [
    {number: "123"},
    {number: "143"},
  ]},
  {paragraph: [
    {number: "197"},
  ]},
]

And I'm really willing to get a object value in return, like this

{articles: [...], paragraph: [...]}

Can someone help me, please?

You could group by the outer properties of the nested objects.

 const array = [{ articles: [{ number: "123" }, { number: "143" }] }, { paragraph: [{ number: "197" }] }], result = array.reduce((r, o) => { Object.entries(o).forEach(([k, a]) => (r[k]??= []).push(...a)); return r; }, {}); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Iterate over the array , and use Object.entries to get the keys and values.

 const array=[{articles:[{number:"123"},{number:"143"}]},{paragraph:[{number:"197"}]}]; const out = {}; for (const obj of array) { const [[key, value]] = Object.entries(obj); out[key] = value; } console.log(out);

This can be done using an array reducer .

 const array = [ { articles: [{ number: "123" }, { number: "143" }] }, { paragraph: [{ number: "197" }] }, ]; const formatted = array.reduce((accumulator, currentValue) => { const [[key, value]] = Object.entries(currentValue); return {...accumulator, [key]: value } }, {}); console.log(formatted);

What we're doing is initializing our reducer with an empty object on line 9, and iterating over the array. Each time we iterate, we're returning the object with the new key and value appended to the end of it.

let array = [
  {articles: [
    {number: "123"},
    {number: "143"},
  ]},
  {paragraph: [
    {number: "197"},
  ]},
]


let obj = {}
array.forEach(a => {

   if('articles' in a){
       obj.articles = a.articles
   }

   if('paragraph' in a){
       obj.paragraph = a.paragraph
   }
})

console.log(obj)

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