简体   繁体   English

我有一个需要在 object (JAVASCRIPT) 中转换的数组

[英]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我真的很愿意得到一个 object 值作为回报,就像这样

{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. 遍历数组,并使用Object.entries获取键和值。

 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 .这可以使用数组 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.我们正在做的是在第 9 行用一个空的 object 初始化我们的 reducer,然后遍历数组。 Each time we iterate, we're returning the object with the new key and value appended to the end of it.每次迭代时,我们都会返回 object,并在其末尾附加新的键和值。

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)

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

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