简体   繁体   中英

Add objects from within JSON array into JavaScript array with keys remapped

I have the following json returned from an ajax request

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

I am trying to add specific pieces of data from the json to an existing js array.

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

I need to add json key id and its matching value - example: "id": key,

I need to add json key task as text with its matching value - example: "text": key

I need to add a "done": "false" to set so a final result would look like:

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

I have no examples of what I have tried as I am not sure where to even begin with this. Keep in mind that json may contain a lot more results.

Use .forEach() to iterate over the 'updates' Array, while destructuring the key / value pairs you want to use

Create your object, then .push() it to the Array

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

You can merge both arrays and then use 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)

If the point here is to simply append and rename keys, it may by done as simple as that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM