1

i have object like:

let obj = {
 type: 1
 name: 'Test'
 pr: 0
 g: 1
}

and i wan't to make like this object with it:

   obj = [
    {
      title: "type",
      value: 1,
    },
    {
      title: "name",
      value: "Test",
    },
    {
      title: "pr",
      value: 0,
    },
    { title: "gr", value: 1 },
  ];

so basically first key will be in name and second key will be value.

What i tried?

 newObj = Object.keys(obj).forEach(function (key) {
        obj = {
          name: key,
          value: key,
        };
      });

it's worked but it's give just first 2 value of the object and not makes object array.

so output is :

obj = {
  name: type,
  value: 1,
};

another entries not visible.

What i need to do ?

1

3 Answers 3

6

You can use Object.entries:

const obj = {
 type: 1,
 name: 'Test',
 pr: 0,
 g: 1
};


const res = Object.entries(obj)
                  .map(([title, value]) => ({title, value}));

console.log(res);

If you're not familiar with this syntax:

([title, value]) => ({title, value})

It could be rewritten as:

function (x) { return { title: x[0], value: x[1] }; }

But in the above example, I used a destructuring assignment to create 2 variables title and value from the provided key/value pair.

And {title, value} is just a shorthand syntax for { title: title, value: value }.

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

3 Comments

I now realize that some of the syntax I used here may be unclear. Don't hesitate if you need an explanation about what's inside the .map(). ([title, value]) is actually a single parameter (the current [key,value] array), but we destructure it into separate variables, using a Destructuring assignment. An then {title, value} is a shorthand syntax for { title: title, value: value}
@blex One suggestion though, add this explanation to answer. People mostly tend to have a look into the answer not comments. I found it is very helpful and informative.
@Karan Thanks for the feedback, I added it
1

You can use Object.keys(...) and use map to get your desired result like below.

Object.keys(obj).map(x => ({ title: x, value: obj[x] }));

const obj = {
  type: 1,
  name: 'Test',
  pr: 0,
  g: 1
};


const res = Object.keys(obj).map(x => ({ title: x, value: obj[x] }));
console.log(res);

Comments

1

Also you can do this by reduce method with Object.keys(), as an alternative:

let obj = {
  type: 1,
  name: 'Test',
  pr: 0,
  g: 1,
}

const result = Object.keys(obj).reduce((acc, rec) => {
  return [...acc, {
    title: rec,
    value: obj[rec]
  }]
}, [])

console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.