简体   繁体   English

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

[英]Create an array of array's of object from Nested Objects

Suppose We have an Array with array of objects like假设我们有一个包含对象数组的数组,例如

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

And we have nestedObj like我们有 NestedObj 之类的

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

Now What I want is basically Using nested object i want to check the array's of object's array value if it exist or not and want to create an array as decleared above.现在我想要的基本上是使用嵌套对象,我想检查对象数组值的数组是否存在,并且想要创建一个如上所述的数组。 Here the count in object is number no.of times the Array of object will appear in above array but.这里对象中的计数是对象数组将出现在上面数组中的次数。 Suppose count is 2 for object proprerty "a" there is already an array of object exist having value "a".假设对象属性“a”的计数为 2,已经存在具有值“a”的对象数组。 i want another array to be pushed number of time's the count but already exist 1 so 1 more time i will add it.我想要另一个数组被推送的次数是计数但已经存在 1 所以我会再添加 1 次。 What I need is from Obj:我需要的是来自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"}],
];

The question doesn't really seems to make much sense in my opinion, but here it is:在我看来,这个问题似乎没有多大意义,但这里是:

 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);

Comments in the snippet explains what is done.代码段中的注释解释了所做的事情。

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

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