0

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 
    })
1
  • 2
    _ contains your key Commented Apr 11, 2019 at 17:24

4 Answers 4

3

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 
})
Sign up to request clarification or add additional context in comments.

1 Comment

Minor note: key will be a string, if Id is supposed to be a number, you probably want Id: +key.
2

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

2 Comments

Object.assign([], students) is clever.
While the Object.assign call is clever, it's perhaps a bit too clever, as it will only work properly if the keys are 0, 1, 2, etc., albeit in any order. Object.entries(students).map(...) is clearer and less fragile.
2

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)

Comments

1

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)

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.