I'm struggling to convert this file so that the clientID is the key on the Object within 'things'. I want to flatten the array and then have keys for each Object within an outer Object.
{
"id": "575802",
"things": [{
"clientId": "123456",
"val": "file1"
},
{
"clientId": "1234",
"val": "file2"
}
]
}
The above I want to be
{
"id":"575802",
"things":{
"123456":{
"val":"file1"
},
"1234":{
"val":"file2"
}
}
}
I've tried using various ways of using Object.entries but I can't find something specific for the purpose of getting an ID out to be the key
You can use reduce()
on things
array
const obj = {
"id": "575802",
"things": [{
"clientId": "123456",
"val": "file1"
},
{
"clientId": "1234",
"val": "file2"
}
]
}
obj.things = obj.things.reduce((ac,{clientId,...rest}) => (ac[clientId] = rest, ac), {})
console.log(obj)
You can use reduce to create the things
key in the required object. In reduce
callback function return an object
let data = {
"id": "575802",
"things": [{
"clientId": "123456",
"val": "file1"
},
{
"clientId": "1234",
"val": "file2"
}
]
}
let newData = {
id: data.id,
things: data.things.reduce(function(acc, curr) {
acc[curr.clientId] = {
val: curr.val
}
return acc;
}, {})
};
console.log(newData)
This might not be an ideal solution (based on how dynamic you need the solution to be).
But here is the fastest solution I came up with.
const data = {
id: '575802',
things: [{
clientId: '123456',
val: 'file1'
},
{
clientId: '1234',
val: 'file2'
}
]
};
const resultObj = {};
resultObj['id'] = data['id'];
resultObj['things'] = {};
const things = data['things'];
for (const thing of things) {
const clientId = thing['clientId'];
resultObj['things'][clientId] = {val: thing['val']};
}
console.log(resultObj);
All I am doing here is iterating over the 'things' property and flattening it into the desired object.
Firebase Cloud Functions: PubSub, "res.on is not a function"
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
this function filters the cities array according to the condition that they should match the wordToMatch and is part of ajaxi tried using console
I am working on a school assignment and I want to inherit the properties of a previous constructor functionI used object
Is there a simple way to convert a string to title case? Eg
I'm currently trying to make a regex to remove every of those character [0-9] \ - * \' if they are either at the beginning of the string, end of the string or if they are consecutive in a string