简体   繁体   English

摆脱 javascript 中的数组

[英]Get rid of an array in javascript

There is an array for each id key that is not needed.每个不需要的 id 键都有一个数组。 That is kind of a group break.那是一种集体休息。

const header = [
[
{ id: "1",
   text: "A",
},
],
[
{ id: "2",
  text: "B",
  array:[1,2,3],
},
{ id: "2",
  text: "B1",
},
],
[
{ id: "3",
  text: "A",
},
],
];

The result should be that below.结果应该是下面的。 The array between the same id should disapear.相同 id 之间的数组应该消失。 Only one array that contains the data as objects should remain.只应保留一个包含数据作为对象的数组。

const header = [
{ id: "1",
  text: "A",
},
{ id: "2",
  text: "B",
  array:[1,2,3],
},
{ id: "2",
   text: "B1",
},
{ id: "3",
   text: "A",
},
];

What you're trying to archive is called flatten.您要归档的内容称为展平。
JavaScript has the build in method to archive this: Array.prototype.flat() . JavaScript 有内置方法来归档这个: Array.prototype.flat()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

Example (taken from the source above)示例(取自上面的来源)

 const arr1 = [0, 1, 2, [3, 4]]; console.log(arr1.flat()); // expected output: [0, 1, 2, 3, 4] const arr2 = [0, 1, 2, [[[3, 4]]]]; console.log(arr2.flat(2)); // expected output: [0, 1, 2, [3, 4]]

You might have to use nested loops, since every index of an array is also an array and push items in an new array.您可能必须使用嵌套循环,因为数组的每个索引也是一个数组并将项目推送到一个新数组中。

const header = [
    [{ id: '1', text: 'A' }],
    [
        { id: '2', text: 'B', array: [1, 2, 3] },
        { id: '2', text: 'B1' },
    ],
    [{ id: '3', text: 'A' }],
];

const newHeader = [];
header.forEach(headerItems => {
    headerItems.forEach(headerItem => {
       newHeader.push(headerItem)
    });
})

console.log(newHeader);

You can using flat() method.您可以使用 flat() 方法。

This link is related about flat method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat此链接与平面方法相关: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

This is my code:这是我的代码:

 // before const header = [ [{ id: '1', text: 'A' }], [ { id: '2', text: 'B', array: [1, 2, 3] }, { id: '2', text: 'B1' } ], [{ id: '3', text: 'A' }] ] // expected output const headerFlat = [ { id: '1', text: 'A' }, { id: '2', text: 'B', array: [1, 2, 3] }, { id: '2', text: 'B1' }, { id: '3', text: 'A' } ] // using flat() const flat = header.flat() console.log(flat)

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

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