How to modify the array object to object in javascript.
I have object obj1
, change the value of details key to new object javascript
function newObj(obj1){
return Object.assign({}, ...obj1.map(e=>(e.details)));
}
var r1= this.newObj(obj1)
var obj1 = [
{
details: {
"info":["stocks","finance",""],
"sales":["analytics"]
}
}
]
var obj2 = [
{
details: {
"city":{"SG"}
}
}
]
Expected Output
//for obj1 (show only first value of array)
{
stocks: "stocks",
analytics: "analytics"
}
//obj2
{
SG: "SG"
}
The object in obj2
should have keys.
To solve this problem, we need to keep an object/map to fill it with the values to be returned by the function. Therefore, you need to iterate over each detail
element and get the values of each property. Then, we can check whether it's an array
or object
and fill the map
accordingly:
var obj1 = [ { details: { "info":["stocks","finance",""], "sales":["analytics"] } } ] var obj2 = [ { details: { "city":{name:"SG"} } } ] function newObj(obj1){ let map = {}; obj1.forEach(e=>{ let details = e.details; Object.values(details).forEach(value => { if(Array.isArray(value) && value.length>0) map[value[0]]=value[0]; else if(typeof value === 'object') Object.values(value).forEach(val => { map[val]=val; }); }) }); return map; } var r1= this.newObj(obj1) console.log(r1); var r2 = this.newObj(obj2) console.log(r2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.