简体   繁体   中英

Get array from json using javascript

Server returns me such object, but i need only array ITEMS. How can i get it? I tried array['items'] but the result is undefiend

{
   "items": [
    {
      ..
    },
    {
      ..
    },
    {
      ..
    }
  ],.. 
  ,..
}
// JSON string returned from the server
var text = '{"items":[{"name":"itemX" ,"price":15},{"name":"itemY","price":25},{"name":"itemZ","price":20}]}';

// Convert the string returned from the server into a JavaScript object.
var object = JSON.parse(text);

// Accessing a specific property value of an item
console.log(object.items[0].name); //itemX

// Extract 'items' in to a separate array
var itemsArray = object.items;
console.log(itemsArray); //[itemObject, itemObject, itemObject]

If you're getting this as a string:

var json = JSON.parse(my_json_string)

Then,

var keys = Object.keys(json);
var values = [];
for(var i = 0; i < keys.length; i++){
    values.push(json[keys[i]]);
}

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