[英]How to get the object key and value into an array in JS?
我有一個對象
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
})
鍵是entrys數組中的第一個元素
var array = Object.entries(students).map(([key, student ]) =>
({
Name: student.replace(/_/g, " "),
Id: key,
Value: student
})
Object.entries返回[key, value]
因此在您的代碼中_
是key
您可以使用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)
您可以將對象分配給數組並映射對象。
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; }
一種替代解決方案:您可以使用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.