我有一个多维javascript对象数组,我正试图使用它来简单地将单元数组中的id及其密钥整理为一个全新的数组
返回id的最佳解决方案是什么?密钥在其单位数组中,但被颠倒,因此新数组的密钥是单位id
[
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
]
预期输出-只返回以下格式的数组例如
ids = [ 10000282 => 0, 10000340 => 1, 10000341 => 2, 10000334 => 0 ]
因此10000282
将是关键,0
将是数组第一次迭代的值--更新--我可能没有很好地解释输出——输出应该如下,但采用数组格式。
ids[10000282] = 0
ids[10000340] = 1
ids[10000341] = 2
ids[10000334] = 0
所以,我想你想把结果放回一个字典里,用嵌套的id作为关键字,用包装单元为其索引赋值。你可以很容易地做到以下几点:
x = [
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
];
result = x.flatMap(el => el.units.map((e,i) => ({[e.id]: i})));
console.log(result);
使用reduce
:的方法略有不同
const data = [{
units: [{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [{
id: 10000334,
name: "Group 4",
}, ],
},
];
const result = data.reduce(
(total, current) =>
total.concat(current.units.map(({ id }, i) => ({ [id]: i }))),
[]
);
console.log(result);
听起来您希望能够直接访问指向重构为对象或Map的id
属性。
使用使用Object.fromEntries()
创建的对象
const arr = [{ units: [{ id: 10000282, name: "Group 1", }, { id: 10000340, name: "Group 2", }, { id: 10000341, name: "Group 3", },], }, { units: [{ id: 10000334, name: "Group 4", },], },];
const result = Object.fromEntries(arr.flatMap(({ units }) => units.map(({ id }, i) => [id, i])));
console.log(result);
// { '10000282': 0, '10000334': 0, '10000340': 1, '10000341': 2 }
console.log('result[10000340] = ', result[10000340])
// result[10000340] = 1
使用地图
const arr = [{ units: [{ id: 10000282, name: "Group 1", }, { id: 10000340, name: "Group 2", }, { id: 10000341, name: "Group 3", },], }, { units: [{ id: 10000334, name: "Group 4", },], },];
const result = new Map(arr.flatMap(({ units }) => units.map(({ id }, i) => [id, i])));
// Map(4) { 10000282 => 0, 10000340 => 1, 10000341 => 2, 10000334 => 0 }
console.log('result.get(10000340) = ', result.get(10000340))
// result.get(10000340) = 1
const arrays = [
{
units: [
{
id: 10000282,
name: "Group 1",
},
{
id: 10000340,
name: "Group 2",
},
{
id: 10000341,
name: "Group 3",
},
],
},
{
units: [
{
id: 10000334,
name: "Group 4",
},
],
},
];
const results = arrays.flatMap((items) => items.units.map(({id}, index) => `ids[${id}] = ${index}`));
console.log(...results);