Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
i have this object
var arr = {
specss: [{
moe: 1,
spec: [{
specID: 4,
cat: [{
catID: 6,
}],
},
{
specID: 11,
cat: [{
catID: 7,
}],
}],
}],
};
I am trying to reduce it to a simpler form.
I have tried looping through them but I always get the first item in the spec not all the items inside
this is my desired output
[{
moe: 1,
spec: [
{
specID: 4,
catID: 6,
},
{
specID: 11,
catID: 7,
},
],
}];
Just change arr to be arr.specss, then loop over every spec of the resulting array, moving the .catID property of the first cat object into the spec object. Like this:
var arr = {
specss: [{
moe: 1,
spec: [{
specID: 4,
cat: [{
catID: 6,
}],
},
{
specID: 11,
cat: [{
catID: 7,
}],
}],
}],
};
arr = arr.specss;
for (const specs of arr) {
for (const spec of specs.spec) {
spec.catID = spec.cat[0].catID;
delete spec.cat;
}
}
console.log(arr)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have array of objects where I want to filter and combine results based on specific id. This is example:
[
{
id: 1,
items: [
{
id: 10,
values: [11],
},
{
id: 20,
values: [13, 14, 15],
},
],
},
{
id: 2,
items: [
{
id: 10,
values: [12],
},
{
id: 20,
values: [13, 15],
},
],
},
];
And this is expected result:
[
{
id: 10,
values: [11, 12],
},
{
id: 20,
values: [13, 14, 15],
},
];
I also need to filter duplicates. Thanks
Note: What if I want this result?
[
{
// here I want value for id 10 (it will be always one number)
value: 11,
// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13, 14, 15],
},
{
// here I want value for id 10 (it will be always one number)
value: 12,
// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13, 15],
},
];
I tried the same approach with Map, but without success. Basically I want to combine values based on ids.
You could do with Array.flatMap to filter all items in single array.
Then recreate the array with Array.reduce and push the value based on id into new value object
And use Array.filter ignore the duplicate values on array
Object.values return only the value of object in array format
Older
const arr = [ { id: 1, items: [ { id: 10, values: [11], }, { id: 20, values: [13, 14, 15], }, ], }, { id: 2, items: [ { id: 10, values: [12], }, { id: 20, values: [13, 15], }, ], }, ];
const res = Object.values(arr.flatMap(({items})=> items)
.reduce((acc,{id,values})=>{
acc[id] = acc[id] ?? {id,values:[]};
//check the object exist or not
let newArr = acc[id]['values'].concat(values);
let valArr = newArr.filter((v,i)=>newArr.indexOf(v) === i)
//remove the duplicates
acc[id]['values'] = valArr
return acc
},{}))
console.log(res)
Updated
const arr = [ { id: 1, items: [ { id: 10, values: [11], }, { id: 20, values: [13, 14, 15], }, ], }, { id: 2, items: [ { id: 10, values: [12], }, { id: 20, values: [13, 15], }, ], }, ];
function filterMethod(arr,value,values){
return arr.map(({items})=> ({
value:detector(items,value)[0],
values:detector(items,values)
}))
}
function detector(items,idVal){
let ind = items.findIndex(({id})=> id === idVal);
return ind > -1 ? items[ind]['values'] : ['']
}
console.log(filterMethod(arr,10,20))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have an object:
obj ={
"AAA": 1,
"BBB": 4,
"CCC": 2,
"DDD": 1,
"EEE": 1,
"FFF": 2,
"AAA_TOTAL": 1,
"BBB_TOTAL": 13,
"GGG": 1,
"HHH": 1,
"III": 14,
"JJJ": 35,
"JJJ_TOTAL": 7,
"KKK": 2,
"LLL": 6,
"MMM_TOTAL": 1,
"OOO": 3,
"PPP": 1
}
now I want to sum up the values of a property that includes TOTAL and has that property name included; Eg:
I want to sum up the values of AAA and similar property AAA_TOTAL => so the output would be :
obj["AAA"] + obj["AAA_TOTAL"]; => o/p would be 2
the TOTAL word can be attached to any property up there. example: it can also be: GGG_TOTAL
in this case, I want to sum up GGG + GGG_TOTAL
Other ex:
obj["BBB_TOTAL"] + obj["BBB"] => o/p would be 17
the final object should looks like:
obj2 ={
"AAA": 2, (sum up value of "AAA_TOTAL": 1)
"BBB": 17,( sum up value of "BBB_TOTAL": 13)
"CCC": 2,
"DDD": 1,
"EEE": 1,
"FFF": 2,
"GGG": 1,
"HHH": 1,
"III": 14,
"JJJ": 42,(sum of "JJJ_TOTAL": 7)
"KKK": 2,
"LLL": 6,
"MMM": 1, (just removing the TOTAL string here and reatining the value as no "MMM" is present to sum)
"OOO": 3,
"PPP": 1
}
this is not a static list of properties and is subject to change, hence I cannot use a hard coded condition.
code:
for (const [key, value] of Object.entries(obj)) {
op={};
id = key.replace(/_total$/gi,'');
op[id] = op[id] || 0;
op[id] += value;
console.log(op)
}
this does not give me desired o/p: it gives this which I'm not looking for:
obj ={
"AAA": 1,
"BBB": 4,
"CCC": 2,
"DDD": 1,
"EEE": 1,
"FFF": 2,
"AAA": 1,
"BBB": 13,
"GGG": 1,
"HHH": 1,
"III": 14,
"JJJ": 35,
"JJJ": 7,
"KKK": 2,
"LLL": 6,
"MMM": 1,
"OOO": 3,
"PPP": 1
}
this just removes the "TOTAL" string from property but does not remove that property itself and does not sum.
any help??
const newObj = Object.keys(obj2).reduce((acc, key) => {
if (key.indexOf('_TOTAL') === -1) {
acc[key] = obj2[key] + (obj2[`${key}_TOTAL`] || 0);
}
return acc;
}, {}),
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have two arrays
var arr1 = [
{id: 1, name:'Rick'},
{id: 2, name:'Daryl'},
{id: 3, name:'Carl'},
{id: 4, name:'Negan'}
];
var arr2 = ['Colt', 'Crossbow', 'Glock', 'Bat'];
I want to assign items from arr2 to the arr1 so the final result would be something like this
arr1 = [
{id: 1, name: 'Rick', weapon: 'Colt'},
{id: 2, name: 'Daryl', weapon: 'Crossbow'},
{id: 3, name: 'Carl', weapon: 'Glock'},
{id: 4, name: 'Negan', weapon: 'Bat'}
];
What is the best approach to achieve this? Any suggestion/example will be appreciated!
You can use Array.prototype.forEach with a value and an index to modify arr1:
arr2.forEach((v, i) => arr1[i].weapon = v);
Or if you don't like forEach you can use map and spread
var arr1 = [
{id: 1, name:'Rick'},
{id: 2, name:'Daryl'},
{id: 3, name:'Carl'},
{id: 4, name:'Negan'}
];
var arr2 = ['Colt', 'Crossbow', 'Glock', 'Bat'];
result = arr1.map((pr, index) => ({...pr, weapon: arr2[index]}))
console.log(result);
var arr1 = [
{id: 1, name:'Rick'},
{id: 2, name:'Daryl'},
{id: 3, name:'Carl'},
{id: 4, name:'Negan'}
];
var arr2 = ['Colt', 'Crossbow', 'Glock', 'Bat'];
arr2.forEach((value, index) => {
arr1[index].weapon = value
// OR
arr1[index]['weapon'] = value
// OR
Object.defineProperty(arr1[index], "weapon", {
value: value,
writable : true,
enumerable : true,
configurable : true });
})
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have the following arrays a and b as shown:
var a = [
{id: 1, name: "phone"},
{id: 2, name: "nick"}
];
var b = [
{id: 7, parentId: 1, name: "phone_item1"},
{id: 8, parentId: 2, name: "phone_item2"},
{id: 9, parentId: 1, name: "nick_item1"},
{id: 10, parentId: 2, name: "nick_item2"}
];
//You want to filter by A array id
const filterIds = a.map(({ id }) => id);
//My attempt
const c = Object.values(b.reduce((r, c) => {
r[c.parentId] = r[c.parentId] || [];
r[c.parentId].push(c);
return r;
}, {}));
console.log(c)
I am trying to obtain the following two-dimensional array:
[[
{id: 7, parentId: 1, name: "phone_item1"},
{id: 9, parentId: 1, name: "nick_item1"}
],[
{id: 8, parentId: 2, name: "phone_item2"},
{id: 10, parentId: 2, name: "nick_item2"}
]]
The resulting array should be according to the comparison between the id of array a and parentId of array b, so that this style of 2D array results. For some reason my attempt is not working - can you help me?
Not suring if I'm missing something here - assuming I understand your question correctly, a simple implementation would be to map each item of a such that the mapping returns a filtered subset of b on matches between bItem.parentId === aItem.id (where aItem and bItem are items of respective lists being iterated):
var a = [
{id: 1, name: "phone"},
{id: 2, name: "nick"}
];
var b = [
{id: 7, parentId: 1, name: "phone_item1"},
{id: 8, parentId: 2, name: "phone_item2"},
{id: 9, parentId: 1, name: "nick_item1"},
{id: 10, parentId: 2, name: "nick_item2"}
];
/* Map each item in a to a classification of b against a */
const result = a.map(aItem => {
/* For current aItem, return a subset of b, filtered by matches
on bItem.parentId === aItem.id (ie the classification criteria) */
return b.filter(bItem => bItem.parentId === aItem.id)
});
console.log(result)
Type error c.paentId and relation for filterIds which was missing:
var a = [
{id: 1, name: "phone"},
{id: 2, name: "nick"}
];
var b = [
{id: 7, parentId: 1, name: "phone_item1"},
{id: 8, parentId: 2, name: "phone_item2"},
{id: 9, parentId: 1, name: "nick_item1"},
{id: 10, parentId: 2, name: "nick_item2"}
];
const filterIds = a.map(({ id }) => id);
//The problem code
const c = Object.values(b.reduce((r, c) => {
r[c.parentId] = filterIds.includes(c.parentId) && r[c.parentId] || [];
r[c.parentId].push(c);
return r;
}, {}));
console.log(c);
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I have an array of objects like this:
var myArray = [{
key: 2,
value: 10,
},
{
key: 5,
value: 4,
},
{
key: 3,
value: 8,
},
{
key: 12,
value: 4,
}];
How is the most elegant way to convert this array in other just with the key numbers: [2,5,3,12]?
Use array.map
var myArray = [{
key: 2,
value: 10,
},
{
key: 5,
value: 4,
},
{
key: 3,
value: 8,
},
{
key: 12,
value: 4,
}];
console.log(myArray.map(a => a.key));
Use .map:
const myKeys = myArray.map(i => i.key);