0

I wanted to iterate the keys and values to be an array in es6 or react. Pls check my code below:

const newData = {
    "id": 111,
    "name": "ewfwef",
    "description": "Hello"
}

const data = Object.keys(newData).forEach((item) => {console.log("item", newData[item])})

EXPECTED OUTPUT

[
  {
    key: id,
    value: 111
  }, 
  {
    key: name,
    value: 'ewfef'
  },
  {
    key: description,
    value: 'Hello'
  }
]
4
  • Asking the same question again (with less information) because the other was closed doesn't make the question any better... Commented Sep 7, 2021 at 8:17
  • React isn't relevant here; and your callback function logs the literal string "item" instead of the item variable's value. Commented Sep 7, 2021 at 8:18
  • you can use declarative syntax: Object.keys(newData).map(item => [{item, newData[item]}]) Commented Sep 7, 2021 at 8:18
  • const data = Object.entries(newData).map(([key, value]) => ({ key, value })); Commented Sep 7, 2021 at 8:21

2 Answers 2

1

Instead of using forEach, you can use the map to get the desired result

const newData = {
  id: 111,
  name: "ewfwef",
  description: "Hello",
};

const data = Object.keys(newData).map((key) => ({ key, value: newData[key] }));

console.log(data);

You can add two keys in two ways:

1) If you don't want to change the resulting array then you can push elements in the array

const newData = {
  id: 111,
  name: "ewfwef",
  description: "Hello",
};

const data = Object.keys(newData).map((key) => ({ key, value: newData[key] }));
data.push({ key: "day", value: "monday" });
data.push({ key: "week", value: "7th" });

console.log(data);

2) Or you can both key-value in the source object

const newData = {
  id: 111,
  name: "ewfwef",
  description: "Hello",
  day: "monday",
  week: "7th",
};

const data = Object.keys(newData).map((key) => ({ key, value: newData[key] }));
console.log(data);

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

16 Comments

"Instead of..." - Or just close it as an obvious dupe.
Thank you, on top of that, how do you a static key value pair if you want? Thanks\
what do you mean by static key-value pair
Let's say you want to add this {day: 'Monday', week: '7th'} on that on this Object.keys(newData).map((key) => ({ key, value: newData[key] })); ?
where do you want to add? In the result array? If yes then you need to specify the position because result is an array.
|
0

You can use Object.entries and map to achieve this,

  const newData = {
        "id": 111,
        "name": "ewfwef",
        "description": "Hello"
    }
    
    const data = Object.entries(newData).map(function(item) {
      return {key: item[0], value: item[1]};
    });
    
    console.log(data)

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.