I have a json Object like following.
{987: "sqa", 988: "Squad"}
I need to change the structure like following
[{id:987, value:'sqa'}, {id:988, value:'Squad'}]
How to do this with Javascript?
I have a json Object like following.
{987: "sqa", 988: "Squad"}
I need to change the structure like following
[{id:987, value:'sqa'}, {id:988, value:'Squad'}]
How to do this with Javascript?
You could get the entries of the object and map new objects in an array.
Techniques:
Object.entries
for getting all key/value pairs from an object in an array,
Array#map
, for mapping a new item for each item of the array,
destructuring assignment for the key/value pair and
short hand properties for taking the name as key and the value as value for an object.
var object = { 987: "sqa", 988: "Squad" },
result = Object.entries(object).map(([id, value]) => ({ id, value }));
console.log(result);
You have written invalid JSON in your question, but I assume you want it as a JavaScript object.
Something like this perhaps.
var oldObj = {
987: "sqa",
988: "Squad"
}
var newArray = [];
for (let k in oldObj) {
newArray.push({'id': k, 'value': oldObj[k]});
}
console.log(newArray);
const intial = {987: "sqa", 988: "Squad"}
const final = [];
for(let idNum in intial){
const data = {
id: idNum,
value: intial[idNum]
}
final.push(data);
}
console.log(final); //[ { id: '987', value: 'sqa' }, { id: '988', value: 'Squad' } ]
This will achieve what you're trying to do