[英]How to access and sort keys in nested objects in Javascript?
我有一個像這樣的嵌套 object
info ={
"id-1":
{
name: Jane,
age: 35,
experience: "7+",
position: manager,
},
"id-2":
{
age: 38,
name: John,
position: manager,
experience: "9+",
},
"id-3":
{
age: 42,
experience: "12+",
position: manager,
name: Max,
}
我有一個字符串
let myString ="name, age,position, experience"
我需要訪問對象中的鍵(姓名、年齡、position、經驗)並根據此字符串對其進行排序,因此 object 中的鍵的順序與 myString 中的順序相同,如下所示:
"id-1":
{
name: Jane,
age: 35,
position: manager,
experience: "7+",
},
如何訪問嵌套對象中的鍵並按順序對其進行排序? 當我嘗試使用 Object.keys(info) 時,它返回id-1、id-2、id-3而不是姓名、年齡、position、經驗。 請幫忙,我似乎無法想出辦法。
首先,您的鍵的大部分值都是無效的。 例如7+
不是string
、 number
或boolean
,如果manager
和John
這樣的詞沒有引號,它們將被視為變量。 所以你的數據需要修復。
接下來,不要將對象包裝在只有順序鍵名的 object 中(破折號是鍵名中的非法語法,除非順便引用了鍵名),只需將所有對象放在一個數組中。
然后,只需遍歷數組中的對象,並按照您想要的順序手動提取您想要的各個鍵值。 無需考慮重新排序它們的存儲順序。
let info = [ {name: "Jane", age: "35", experience: "7+", position: "manager" }, {age: "38", name: "John", position: "manager", experience: "9+"}, {age: "42", experience: "12+", position: "manager", name: "Max"} ]; let keyNames = ["name", "age", "position", "experience"]; // Loop over the objects in the array info.forEach(function(obj){ let output = ""; // Will hold the output for one object at a time // Loop over the key names in the array so we go in the desired order keyNames.forEach(function(key){ // Build up the string with they key name and the key value output += key + ": " + obj[key] + " "; }); console.log(output); // Write out the string for the object });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.