Search code examples
javascriptjqueryarraysjsonobject

how to add two javascript objects


i have problem with javascript objects i want to add two objects structure same here they are also first of all they objects is string

data1 = '{"display:[{"counter":"A023","token":"001"}]"}'
data2 = '{"display:[{"counter":"A013","token":"003"}]"}'

expected result new

data = '{"display:[{"counter":"A023","token":"001"}, {"counter":"A013","token":"003"}]"}'

i have tried these codes

var data1 = JSON.parse(data1);
var data1 = JSON.parse(data1);
var newdata = $.merge(data1.display, data2.display);

i cant solve this problem, i don't know how to do it I also tried other codes


Solution

  • Try this:

    let data1 = '{"display":[{"counter":"A023","token":"001"}]}'
    let data2 = '{"display":[{"counter":"A013","token":"003"}]}'
    
    data1 = JSON.parse(data1);
    data2 = JSON.parse(data2);
    
    data = JSON.stringify({display: [...data1.display, ...data2.display]})
    console.log(data)