簡體   English   中英

使用重新映射的鍵將 JSON 數組中的對象添加到 JavaScript 數組中

[英]Add objects from within JSON array into JavaScript array with keys remapped

我從 ajax 請求返回了以下 json

[
  {
    "id": "1",
    "task": "eat pizza",
    "username": "all"
  },
  {
    "id": "2",
    "task": "drink soda",
    "username": "all"
  }
]

我正在嘗試將特定的數據從 json 添加到現有的 js 數組。

this.$todoData2 = [
    {
        'id': '5',
        'text': 'Cheese',
        'done': false
    },
]

我需要添加 json 密鑰 ID 及其匹配值 - 例如:“id”:key,

我需要將 json 關鍵任務添加為具有匹配值的文本 - 例如:“text”:key

我需要添加一個 "done": "false" 來設置,以便最終結果如下所示:

this.$todoData2 = [
    { 
        "id": "1",
        "text": "eat pizza",
        'done': false
    }
    { 
        "id": "2",
        "text": "drink soda",
        'done': false
    }
    {
        'id': '5',
        'text': 'Cheese',
        'done': false
    },
]

我沒有我嘗試過的例子,因為我不知道從哪里開始。 請記住,json 可能包含更多結果。

使用.forEach()迭代“更新”數組,同時解構要使用的鍵/值對

創建你的對象,然后.push()到數組

 const $todoData2 = [ {'id': '5', 'text': 'Cheese', 'done': false}, ]; const update = [ {"id": "1", "task": "eat pizza", "username": "all"}, {"id": "2", "task": "drink soda", "username": "all"} ]; update.forEach(({id, task}) => { $todoData2.push({ 'id': id, 'text': task, 'done': false }); }); console.log($todoData2);

您可以合並兩個數組,然后使用map

 let arr = [ { "id": "1", "task": "eat pizza", "username": "all" }, { "id": "2", "task": "drink soda", "username": "all" } ] let todoData2 = [ { 'id': '5', 'text': 'Cheese', 'done': false }, ] todoData2 = todoData2.concat(arr).map( obj => ({ id:obj.id, text:obj.task || obj.text , done:false }) ); console.log(todoData2)

如果這里的重點是簡單地附加和重命名鍵,它可以像這樣簡單地完成:

 const newItems = [{"id":"1","task":"eat pizza","username":"all"},{"id":"2","task":"drink soda","username":"all"}], existingItems = [{"id":"5","text":"Cheese","done":false}] existingItems.push(...newItems.map(({id,task:text}) => ({id,text,done:false}))) console.log(existingItems)
 .as-console-wrapper{min-height:100%}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM