skip to Main Content

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.

3

Answers


  1. 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);
    Login or Signup to reply.
  2. 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)
    Login or Signup to reply.
  3. 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%}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search