简体   繁体   中英

How to convert json array to json object in js

Actually i am trying to populate a list of years using canjs.

CATEGORIES is the existing json object

var CATEGORIES = [
    {
        id: 1,
        year: '1983'
    },
    {
        id: 2,
        year: '1984'
    },
    {
        id: 3,
        year: '1985'
    }
];

and remaining from database using can.ajax and slim frame work.... i can able to get the details from database using can ajax and json encode...now my problem is how can i add these fetched json array to existing json object...i tryed below code..

var CATEGORIES = [
    {
        id: 1,
        year: 'Family'
    },
    {
        id: 2,
        year: 'Friends'
    },
    {
        id: 3,
        year: 'Co-workers'
    }
];

can.ajax({
url: 'api/years',
error: function (xhr, ajaxOptions, thrownError) {
                 alert(xhr.status);
                   alert(thrownError);
alert(xhr.responseText);
                 },
success: function(CATEGORIES1) {
alert(CATEGORIES1); // output: [{"id":"1","year":"1986"},{"id":"2","year":"1987"}]
CATEGORIES = JSON.stringify(eval("(" + CATEGORIES1 + ")"));
alert(CATEGORIES); // output:[{"id":"1","year":"1986"},{"id":"2","year":"1987"}]
}
});


alert(CATEGORIES); // output:[object Object],[object Object],[object Object]

我相信您想要的是用ajax返回的新数组连接现有数组:

CATEGORIES = CATEGORIES.concat(CATEGORIES1)

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