0

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

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

That's a computed property name - it puts a property on the object such that the property name is the expression inside the []s
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.