Reputation: 146
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
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". 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. What I need is from 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"}],
];
Upvotes: 0
Views: 119
Reputation: 7436
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.
Upvotes: 1