How can I loop over this object(data) and return a an array of object (output) just like this. basically with these specific properties and value
data = {
"model-10389": 164703,
"model-10388": 164704,
"model-10387": 164705,
}
const output = [
{
modelId : 10389,
id : 164703
},
{
modelId : 10388,
id : 164704
},
{
modelId : 10387,
id : 164705
},
]
this is what I have now
Object.keys(data).map(function(key, index) {
console.log(data[key])
});
or this
for (const property in data) {
console.log(`${property}: ${data[property]}`);
}
Split the problem up into small parts:
Array.map for that[key, value] array, we can use destructuring in the .map for easy access.modelId, we need to .split the key, and get the part behind the -, then parse it as a number.id is just the value.const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };
const result = Object.entries(data)
.map(([key, value]) => ({
modelId: parseInt(key.split('-')[1], 10),
id: value
}));
console.log(result);
A slightly faster alternative to the split, id to use a regex to extract ids:
modelId: parseInt(key.match(/\d+/)[0], 10),
However, if we're going to go as far as we can to optimize this transform, we're going to have to make a few more changes:
+ instead of parseInt.for in loop instead of Object.entries and .map..splitThat'll get you:
const data = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 };
const result = [];
for (let key in data) {
result.push({
modelId: +key.match(/\d+/)[0],
id: data[key]
});
}
console.log(result);
I'd use Object.entries with object destructuring, short object literal syntax and unary + for conversion to number:
const data = {"model-10389": 164703, "model-10388": 164704, "model-10387": 164705};
const output = Object.entries(data).map(([key, id]) => ({
modelId: +key.replace(/.*-/, ""),
id
}));
console.log(output);
If the key(model-*) in data doesn't change, then you can use substring() with the index.
const data = {
"model-10389": 164703,
"model-10388": 164704,
"model-10387": 164705
}
const result = Object.entries(data)
.map(([key, value]) => ({
modelId: +key.substring(6),
id: value
}));
console.log(result)