【问题标题】:Get rid of an array in javascript摆脱javascript中的数组
【发布时间】:2022-11-19 23:29:28
【问题描述】:

每个不需要的 id 键都有一个数组。那是一种集体休息。

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

结果应该是下面的。相同 id 之间的数组应该消失。只应保留一个包含数据作为对象的数组。

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

【问题讨论】:

  • 这个数组从哪里来?数据库(如果是的话如何?)?从 JavaScript 函数?...

标签: javascript arrays reduce uniq group


【解决方案1】:

您要归档的内容称为展平。
JavaScript 有内置方法来存档:Array.prototype.flat()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

例子(取自上面的来源)

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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2020-11-13
    • 2020-08-08
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多