0

I have an object:

obj= {
  sside: "1",
  id: 222,
  env: "Windows",
  platform: "Windows33",
  model: "IE9"
}

Now I want to convert this above object into this:

obj2 = [{name: "sside", value:"1"},{name:"id", value:"222",name:"env",value:"Windows"}];

I'm able to get all the keys in the array:

var keysArray= Object.keys(obj);

But im not sure how can I assign "name" field to every key inside the keysArray

Is this possible to do?

1
  • I would say no, given that {name:"id", value:"222",name:"env",value:"Windows"} is not a valid object. Are you sure you didn't want [{"name": "sside", "value": "1"},{"name": "id", "value": "222"},{"name": "env", "value": "Windows"}]? Commented Jun 19, 2019 at 22:58

2 Answers 2

2

Try this:

const obj2 = Object.keys(obj).map(key => ({name: key, value: obj[key]}))
Sign up to request clarification or add additional context in comments.

Comments

1

You can loop through the object and get each key and value and push this into an array.

obj = {
  sside: "1",
  id: 222,
  env: "Windows",
  platform: "Windows33",
  model: "IE9"
};

arr = [];


Object.keys(obj)
  .forEach(function splitObj(key) {
    arr.push({name: key, value: obj[key]})
  });

console.log(arr);

1 Comment

That's what map is for.

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.