[英]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" 我有对象的值,但没有“ Id”的键
var array = Object.entries(students).map(([_, student ]) =>
({
Name: student.replace(/_/g, " "),
Id: ?,
Value: student
})
The key is the first element in the entries array 键是entrys数组中的第一个元素
var array = Object.entries(students).map(([key, student ]) =>
({
Name: student.replace(/_/g, " "),
Id: key,
Value: student
})
Object.entries return [key, value]
so in your code _
is key
Object.entries返回
[key, value]
因此在您的代码中_
是key
You can use Object.entries and map and replace 您可以使用Object.entries并映射和替换
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)
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; }
An alternative solution: you can use Object.keys , and iterate through the students
object using the keys. 一种替代解决方案:您可以使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.