How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined

{
   "items": [
    {
      ..
    },
    {
      ..
    },
    {
      ..
    }
  ],.. 
  ,..
}

Answer №1

// Data in JSON format retrieved from the server
var jsonData = '{"items":[{"name":"itemX" ,"price":15},{"name":"itemY","price":25},{"name":"itemZ","price":20}]}' ;

// Converting the JSON data into a JavaScript object
var dataObject = JSON.parse(jsonData);

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

// Separating 'items' into its own array
var itemsArr = dataObject.items;
console.log(itemsArr); //[itemObject, itemObject, itemObject]

Answer №2

When you encounter this situation as a text:

let data = JSON.parse(my_text_string)

You can do the following:

let props = Object.keys(data);
let items = [];
for(let i = 0; i < props.length; i++){
    items.push(data[props[i]]);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Cheerio help you effortlessly and stylishly locate tags that meet various specific criteria?

I am attempting to scrape data from the webpage . Specifically, I am looking for all the <li> tags that are nested within an <ul> tag, which in turn is located inside a div with the class mw-parser-output and has a property of title. Is there ...

Using jq filter to selectively extract key-value pairs in bash

After executing the given command aws ec2 describe-tags --filter "Name=resource-id,Values=i-8dh7435490fjksfd" I received this JSON response { "Tags": [ { "ResourceType": "instance", "ResourceId": "i-8dh7435490fjksf ...

Rotating 3D cube with CSS, adjusting height during transition

I'm attempting to create a basic 2-sided cube rotation. Following the rotation, my goal is to click on one of the sides and have its height increase. However, I've run into an issue where the transition occurs from the middle instead of from the ...

Incorporate the AngularJS controller into your JavaScript code

I am facing an issue with my jQuery UI dialog that contains a dynamic <select> populated with Angular and AJAX. The problem is that the AngularJS script still runs even when the dialog is not visible. To solve this, I added a condition to stop the s ...

The system has removed all content within the fields

I have created a code to generate a dynamic table. The problem I am facing is that when there are multiple rows in the table, clicking on the delete button deletes all field values instead of just deleting the data for the specific row where the delete b ...

Populate a bootstrap-select dropdown menu with an array of choices

After creating a table using datatables and adding an empty dropdown select on the footer with Bootstrap-select, here is the code snippet: <tfoot> <tr> <th><select class="selectpicker" multiple></select>< ...

Instructions for including dependencies from a globally installed npm package into a local package

I've noticed that although I have installed a few npm packages globally, none of them are showing up in any of my package.json files. What is the recommended npm command to automatically add these dependencies to all of my package.json files? ...

Convert a Dictionary containing keys of object types and values as Lists into JSON serialization

I am looking to convert the following Dictionary type into Json: public class Repsonse { public Dictionary<Employee, List<Car>> Dictionary { get; set; } public class Employee { public string Name { get; set; } publ ...

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

Dealing with 404 errors on dynamic routes in Next.js that are utilizing an API: A guide

I have a website built using a combination of React and Next.js on the client side, with APIs from an Asp.Net core server to fetch dynamic data like products and categories. The challenge I'm facing is figuring out how to redirect to a 404 not found ...

Encountering a syntax error with the AngularJS ng-class expression

While navigating through a tutorial application designed for use with the Ionic platform, which is based on angular 1.2.4, I encountered a perplexing error in this Angular markup: <content has-header="true" scroll="false"> <list> ...

Enhance each category changing with jQuery page transitions

Is there a way to add page transitions based on category names and quantities in PHP? For example, when clicking on the "office" category, can a popup overlay be displayed with the category name and quantity while the content loads? The focus is on creat ...

Using PHP to iterate through nested JSON loops

I'm working with a JSON structure that looks like this: [ { “id” : 1, “user_id” : 1, “location” : { “long” : 34.2489234, “lat” : -117.234234, }, “active” : 1 }, { “id” : 2, ...

Scrolling a div automatically without affecting its parent element

On a page, I have a scrollable list of items that can be updated with a PUT request. Once the update is successful, another network request is made to fetch the updated list. The goal is to automatically highlight the recently updated item in the list. Al ...

Creating a JSON file that contains a collection of discord.js statuses and then seamlessly integrating it into the primary JavaScript document

const userActivities = [ { name: "Morning Jog", type: ActivityType.Running }, { name: "Afternoon Nap", type: ActivityType.Sleeping }, { name: "Evening Game Night", type: ActivityType.Gaming }, { name: "Late Night Code ...

The Swashbuckle tool, along with the Swagger pattern and Format annotation, or even the use

I'm currently working on incorporating format and pattern keywords into my Swagger documentation. I am utilizing Swashbuckle and have been using XML Comments to provide descriptions for various fields. Here's an example of how I've been docu ...

Issue with WebRTC, socket.io, and node.js: Unable to access the property 'emit' as it is undefined

Currently, I am in the process of creating a webrtc video app. Within the client code section, the following lines are present: getUserMedia(constraints, handlemedia, errorhandle); constraints = {video: true}; function handlemedia(stream){ //other act ...

"Exploring the Possibilities with WordPress and Waypoint Js

After exploring various resources and tutorials online, I am struggling to implement Waypoints with WordPress. Despite placing the necessary files like waypoints.min.js and waypoints.js in the designated download folder within the js directory of my templa ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Exploring VueJS Router History Mode with NGinx web server

After conducting research, I discovered several issues similar to the one I am facing. Currently, I have a docker-compose setup on Digital Ocean with NGinx, VueJS, and a Static Landing Page. Everything was working fine until I added a new route with a fo ...