简体   繁体   English

从数组和包含另一个数组的属性创建一个新数组

[英]create a new array from array and your property that contains another array

I need create a new array from array and your property that contains another array: 我需要从array和包含另一个数组的属性中创建一个新数组:

bigArray = [
    {
     bigArrayID : 1,
     name: 'Xpto',
     children: [
         {childID:1,Name:'XptoChild1'},
         {childID:2,Name:'XptoChild2'},
     ]
    },
    {
     bigArrayID : 2,
     name: 'Foo',
     children: [
         {childID:3,Name:'FooChild1'},
         {childID:4,Name:'FooChild2'},
     ]
    },
    {
     bigArrayID : 3,
     name: 'Bar',
     children: [
         {childID:5,Name:'BarChild1'},
         {childID:6,Name:'BarChild2'},
     ]
    }
]

turn bigArray as result like: 结果变成bigArray:

result = [
            {
             bigArrayID : 1,
             name: 'Xpto',
             children: [
                 {childID:1,Name:'XptoChild1'},
                 {childID:2,Name:'XptoChild2'},
             ]
            },
            {childID:1,Name:'XptoChild1'},
            {childID:2,Name:'XptoChild2'},
            {
             bigArrayID : 2,
             name: 'Foo',
             children: [
                 {childID:3,Name:'FooChild1'},
                 {childID:4,Name:'FooChild2'},
             ]
            },
            {childID:3,Name:'FooChild1'},
            {childID:4,Name:'FooChild2'},
            {
             bigArrayID : 3,
             name: 'Bar',
             children: [
                 {childID:5,Name:'BarChild1'},
                 {childID:6,Name:'BarChild2'},
             ]
            },
            {childID:5,Name:'BarChild1'},
            {childID:6,Name:'BarChild2'}
        ]

Each children must be a element in new array. 每个子代必须是新数组中的元素。

I need a new array with all father and all child as object. 我需要一个以所有父亲和所有孩子为对象的新数组。

I need turn child as sibling of your father in new array. 我需要把孩子当成新阵列中你父亲的兄弟姐妹。

I think I need use concat and/or spread array function... 我想我需要使用concat和/或spread array函数...

Yes you are correct, you can use Array#reduce() and then Array#concat() each element and its children to the accumulator within the callback: 是的,您是正确的,可以使用Array#reduce() ,然后使用Array#concat()每个元素及其子元素传递给回调中的累加器:

 const bigArray = [{"bigArrayID":1,"name":"Xpto","children":[{"childID":1,"Name":"XptoChild1"},{"childID":2,"Name":"XptoChild2"}]},{"bigArrayID":2,"name":"Foo","children":[{"childID":3,"Name":"FooChild1"},{"childID":4,"Name":"FooChild2"}]},{"bigArrayID":3,"name":"Bar","children":[{"childID":5,"Name":"BarChild1"},{"childID":6,"Name":"BarChild2"}]}] const result = bigArray.reduce( (result, element) => result.concat(element, element.children), [] ) // stringify is simply to prevent side-effects // of stack snippet console behavior console.log(JSON.stringify(result, null, 2)) 

Original 原版的

var resultArray = bigArray.concat(bigArray.map(function(item) {
  return item.children;
})

With order 有订单

var result = [];
for(var i = 0; i < bigArray.length; i++) {
  result.push(bigArray[i]);
  for( var y = 0; y < bigArray[i].children.length; y++) {
    result.push(bigArray[i].children[y]);
  }
}

With functional programming and order 通过功能编程和命令

var result = [];
bigArray.forEach(function(item) {
  result.push(item);
  item.forEach(result.push);
})

Not sure if I understand your question correctly but it seems to me that you want to flatten the hierarchy? 不知道我是否正确理解了您的问题,但在我看来您想展平层次结构? If the ordering is not really important then below solution might helps 如果订购不是很重要,那么下面的解决方案可能会有所帮助

let childArray = [];
bigArray.forEach(x=> {
  childArray = [...childArray, x.children]
});

let answer = [...childArray,...bigArray];

The idea is to loop thru all the father in order to grab all their children and store all children into one array, then merge both the children with father into single array 这个想法是循环遍历所有父亲,以便抓住所有孩子并将所有孩子存储在一个阵列中,然后将两个孩子和父亲一起合并为一个阵列

Array#reduce into Array#concat is known as Array#flatMap , which is currently stage-3. Array#reduceArray#concat被称为Array#flatMap ,当前是第三阶段。 This is also known as #chain according to Fantasy Land Monad spec . 根据Fantasy Land Monad规范,这也称为#chain

You can use it like this 你可以这样使用

const result =
  bigArray .flatMap
    (node => [ node, ...node.children ])

console.log (result)
// [ { bigArrayID: 1, name: 'Xpto', children: [ ... ] }
// , { childID: 1, name: 'XptoChild1' }
// , { childID: 2, name: 'XptoChild2' }
// , { bigArrayID: 2, name: 'Foo', children: [ ... ] }
// , { childID: 3, name: 'FooChild1' }
// , { childID: 4, name: 'FooChild2' }
// , { bigArrayID: 3, name: 'Bar', children: [ ... ] }
// , { childID: 5, name: 'BarChild1' }
// , { childID: 6, name: 'BarChild2' }
// ]

If you don't have it in your environment, you can easily polyfill it 如果您的环境中没有它,则可以轻松地对其进行填充

Array.prototype.flatMap = function (f)
  { return this.reduce
      ( (acc, x) =>
          acc .concat (f (x))
      , []
      )
  }

Run a full demonstration of the program in your browser below 在下面的浏览器中运行该程序的完整演示

 Array.prototype.flatMap = function (f) { return this.reduce ( (acc, x) => acc .concat (f (x)) , [] ) } const bigArray = [ { bigArrayID: 1 , name: "Xpto" , children: [ { childID: 1, name: "XptoChild1" } , { childID: 2, name: "XptoChild2" } ] } , { bigArrayID: 2 , name: "Foo" , children: [ { childID: 3, name: "FooChild1" } , { childID: 4, name: "FooChild2" } ] } , { bigArrayID: 3 , name: "Bar" , children: [ { childID: 5, name: "BarChild1" } , { childID: 6, name: "BarChild2" } ] } ] const result = bigArray .flatMap (node => [ node, ...node.children ]) console.log (result) // [ { bigArrayID: 1, name: 'Xpto', children: [ ... ] } // , { childID: 1, name: 'XptoChild1' } // , { childID: 2, name: 'XptoChild2' } // , { bigArrayID: 2, name: 'Foo', children: [ ... ] } // , { childID: 3, name: 'FooChild1' } // , { childID: 4, name: 'FooChild2' } // , { bigArrayID: 3, name: 'Bar', children: [ ... ] } // , { childID: 5, name: 'BarChild1' } // , { childID: 6, name: 'BarChild2' } // ] 

If you want the indices and context switching like Array#map and Array#reduce and Array#filter provide, you can add those too 如果您想要索引和上下文切换(例如Array#mapArray#reduceArray#filter提供,也可以添加这些索引和上下文

Array.prototype.flatMap = function (f, context)
  { return this.reduce
      ( (acc, x, i) =>
          acc .concat (f .call (context, x, i, this))
      , []
      )
  }

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

相关问题 尝试遍历一组对象,并创建一个新属性,其中包含来自该句子的 text 属性的一组单词 - Trying to iterate over an array of objects, and create a new property that contains an array of words from that sentence's text property 从另一个数组创建一个新数组 - Create a new array from another array 如何基于第三个数组从另一个数组创建一个新数组? - How to create a new array from another array based on third array? 在javascript中的对象数组中从具有空值的数组创建一个新属性 - Create a new property from an array with null value in an array of objects in javascript 创建主数组的修改后属性的新数组 - create an new array of modified property of main array 检查一个数组是否包含来自另一个数组的元素 - Check if an array contains elements from another array 如何将一个数组中的值减去另一个数组并创建一个新数组? - How to subtract value from one array to another and create a new Array? 使用另一个 object 的键从对象数组创建新数组 - Create new Array from array of objects with keys of another object 如何从另一个 JS 数组创建新的 JS 数组 - How to create new JS array from another JS array 使用 JavaScript 中的“减少”从另一个数组创建新数组 - create new array from another array using “reduce” in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM