susu watari
susu watari

Reputation: 207

How to get the object key and value into an array in JS?

I have an object

var students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" }

How can I get an array from the object with its key and value?

var array = [ 
    { "Id": 0, "Value": "Ann_L", "Name": "Ann L" },
    { "Id": 1, "Value": "Bob_P", "Name": "Bob P" },
    { "Id": 2, "Value": "Cat_C", "Name": "Cat C" }
]

I have the values of the object but not the keys for "Id"

var array = Object.entries(students).map(([_, student ]) => 
    ({
        Name: student.replace(/_/g, " "), 
        Id: ?,
        Value: student 
    })

Upvotes: 0

Views: 73

Answers (4)

Code Maniac
Code Maniac

Reputation: 37775

Object.entries return [key, value] so in your code _ is key

You can use Object.entries and map and replace

var students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" }

let op = Object.entries(students).map(([Id,value]) => {
  return {
    Id,
    value,
    name: value.replace(/_/g, ' ')
  }
})

console.log(op)

Upvotes: 2

wentjun
wentjun

Reputation: 42596

An alternative solution: you can use Object.keys, and iterate through the students object using the keys.

const students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" }

const res = Object.keys(students).map((element, index) => {
  return {
    Id: element,
    Value: students[index],
    Name: students[index].replace(/_/g, " "),  
  }
})

console.log(res)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could assign the object to an array and map the objects.

var students = { 0: "Ann_L", 1: "Bob_P", 2: "Cat_C" },
    array = Object
        .assign([], students)
        .map((Value, Id) => ({ Id, Value, Name: Value.replace(/_/g, ' ') }));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

charlietfl
charlietfl

Reputation: 171698

The key is the first element in the entries array

var array = Object.entries(students).map(([key, student ]) => 
({
    Name: student.replace(/_/g, " "), 
    Id: key,
    Value: student 
})

Upvotes: 3

Related Questions