I am trying to combine ids for an object. The original object looks like this:
{
"Car1":{
"139":{
"count":3,
"ids":[
"336",
"347",
"453"
]
},
"140":{
"count":1,
"ids":[
"338"
]
}
},
"Car2":{
"157":{
"count":1,
"ids":[
"4449"
]
}
}
}
I am trying to combine the ids for each "car" so that it looks like this.
{
"Car1":{
"ids":[
"336",
"347",
"453",
"338"
]
},
"Car2":{
"ids":[
"4449"
]
}
}
Basically just trying to create a function that reduces the unneeded information and combines the ids
CodePudding user response:
You may use the Array.reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Object.entries(data)
.reduce((acc, [carName, carData]) => {
acc[carName] = { ids: Object.values(carData).flatMap(({ids}) => ids) };
return acc;
},{});
I further commented each line in the demo:
const data = {
"Car1":{
"139":{"count":3,"ids":["336","347","453"]},
"140":{"count":1, "ids":["338"]}
},
"Car2":{
"157":{"count":1,"ids":["4449"]}
}
};
const transformedData =
//for all property name=>value pairs in data
Object.entries(data)
//return the reduced version...
//for each couple as carName=>carData
.reduce((acc, [carName, carData]) => {
//sets the property carName in the accumulator
acc[carName] = {
//where the id property is the merge of all the ids found in the whole list
ids: Object.values(carData).flatMap(({ids}) => ids)
};
return acc;
},
//inits the accumulator with empty object
{});
console.log(transformedData);
CodePudding user response:
You can try in this way:
const obj = {
"Car1":{
"139":{
"count":3,
"ids":[
"336",
"347",
"453"
]
},
"140":{
"count":1,
"ids":[
"338"
]
}
},
"Car2":{
"157":{
"count":1,
"ids":[
"4449"
]
}
}
}
const objKeys = Object.keys(obj)
let newObj = {}
objKeys.forEach(key =>{
const carObjKeys = Object.keys(obj[key])
let keysArray = [];
carObjKeys.forEach(k =>{
keysArray = keysArray.concat(obj[key][k]['ids'])
})
newObj[key] = {
ids: keysArray
}
})
console.log(newObj)
CodePudding user response:
To combine the IDs for each car in your object and remove the unneeded information, you can use the following function:
function combineIds(obj) {
const combined = {};
for (const car in obj) {
combined[car] = { ids: [] };
for (const id in obj[car]) {
combined[car].ids.push(...obj[car][id].ids);
}
}
return combined;
}
CodePudding user response:
You can use the following function:
function convertObject(obj) {
let res = {};
Object.keys(obj).forEach(key => {
let ids = [];
for(const subKey in obj[key]) {
ids = [...ids, ...obj[key][subKey]["ids"]]
}
res[key] = ids;
})
return res;
}