从嵌套对象创建对象的数组数组



假设我们有一个包含等对象数组的数组

let array = [
[{value:'a',somepros:"old"}],
[{value:'d',somepros:"old"}],
[{value:'b',somepros:"old"}]
];

我们已经嵌套了类似的Obj

let obj ={
"a":{
"count":2
},
"b":{
"count":2
},
"c":{
"count":1
},
"e":{
"count":1
}
};

现在我想要的基本上是使用嵌套对象,我想检查对象的数组值的数组是否存在,并希望创建一个如上所述的decleared数组。这里,对象中的计数是对象的数组在上面的数组中出现的次数,但是。假设计数是2的对象属性";a";已经存在一个具有值"0"的对象数组;a";。我想推送另一个数组,时间是计数,但已经存在1,所以我会再加1次。我需要的是来自Obj:

NewArr =[
[{value:'a',somepros:"old"}],
[{value:'a',somepros:"newpushed"}],
[{value:'b',somepros:"old"}],
[{value:'b',somepros:"newpushed"}],
[{value:'c',somepros:"newpushed"}],
[{value:'e',somepros:"newpushed"}],
];

在我看来,这个问题似乎没有多大意义,但它是:

let array = [
[{value:'a',somepros:"old"}],
[{value:'d',somepros:"old"}],
[{value:'b',somepros:"old"}]
],
obj ={
"a":{
"count":2
},
"b":{
"count":2
},
"c":{
"count":1
},
"e":{
"count":1
}
};
const res = [];
// loop each entry from obj.
for (const [key, {count}] of Object.entries(obj)) {
// check whether the key exists in the original array.
const matched = array.find((arr) => arr[0].value === key);
// If it exists, push it.
if (matched) res.push(matched);
// then, add X elements "newpushed", where X is given by the count declared - 0 if matched doesn't exist, otherwise 1 (since an element already existed).
res.push(
...Array.from({length: (count - (matched ? 1 : 0))}, (_) => ([{ value: key, somepros: 'newpushed' }]))
);
}
console.log(res);

代码段中的注释解释了所做的操作。

最新更新