如何将对象的键和值放入JS中的数组?

时间:2019-04-11 17:21:07

标签: javascript object

我有一个对象

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

如何从对象及其键和值中获取数组?

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" }
]

我有对象的值,但没有“ Id”的键

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

4 个答案:

答案 0 :(得分:3)

键是条目数组中的第一个元素

GetVissionDetectionStateAsync()

答案 1 :(得分:2)

Object.entries 返回[key, value],因此在您的代码中_key

您可以使用Object.entriesmapreplace

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)

答案 2 :(得分:2)

您可以将对象分配给数组并映射对象。

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

答案 3 :(得分:1)

另一种解决方案:您可以使用Object.keys,并使用键来遍历students对象。

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)