Reputation: 85
I have an object.
var x = {"id":"asc","metaid":"desc"}
I want to create another object which looks something like this.
[{id: {order:"asc"}},{metaid: {order:"desc"}}]
What I have already tried is this
const sc1 = [];
var def1 = {}
for (let key of Object.keys(obj)){
def1[key] = {order: obj[key]}
}
sc1.push(def1);
The above code doesn't give required output. Need help with this. Thanks
Upvotes: 0
Views: 48
Reputation: 3122
You can use Array#from
var x = {"id":"asc","metaid":"desc"};
let out = Array.from(Object.entries(x), ([prop, value]) => ({[prop]: {order: value}}));
console.log(out)
Upvotes: 1
Reputation: 370679
Map the entries of the object to return an object with a computed property name:
var x = {"id":"asc","metaid":"desc"};
const result = Object.entries(x)
.map(([prop, order]) => ({ [prop]: { order } }));
console.log(result);
Upvotes: 2