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

Unable to fetch a new session from the selenium server due to an error

I'm currently in the process of setting up Nightwatch.js for the very first time. I am following the tutorial provided at this link: https://github.com/dwyl/learn-nightwatch Unfortunately, I have encountered a barrier and require assistance to resolv ...

JavaScript tip: Improve the way you highlight the current navigation page while scrolling by finding alternative methods to using "scrollY > x"

Currently, my webpage layout is divided into 4 sections - HOME, ABOUT, SKILLS, and CONTACT. Below is the JavaScript code I am using to highlight a specific section on the navigation bar based on the scroll position: let home = document.querySelector(" ...

Displaying a two-dimensional array from a JSON file using AngularJS ng-repeat

Looking at this HTML file, I am trying to display a 2D array from the json-$scope.listOfIngredient <div class="ingredientMapping" ng-repeat="IngredientMapping in listOfIngredient track by $index"> <ul> <!-- BEGIN: Inner ngRep ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

Having trouble accessing the loadTokenizer function in Tensorflow JS

As a beginner with Tensorflow.js concepts, I recently attempted to tokenize a sentence using the Universal Sentence Encoder in Javascript. You can explore more about it on Github Reference $ npm install @tensorflow/tfjs @tensorflow-models/universal-sentenc ...

Fetch a JSON object from a URL using SwiftUI

I am attempting to utilize a JSON file with a single object stored on a website. My goal is to showcase one of the variables (spot) from the JSON file within the Text inside the ZStack. However, I am encountering an issue with defining the @State variable ...

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

Choose a collection of elements and encase them within a <div> tag

I am currently working on creating a greasemonkey script for a webpage that has a rather challenging structure. My goal is to show and hide different entries, but the content is formatted like this: <a name="first"/> <h3>First</h3> Some ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

Deciphering the evolution of APIs and managing internal API systems

I'm currently exploring the world of APIs and I have a few questions that are puzzling me. Question1: I understand that APIs facilitate communication between different applications. But why would a company need an API for internal use? For example, i ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Vue's getComponentName method now properly returns a function instead of returning 'undefined'

After tirelessly working on upgrading my project from Vue 2.6 to 2.7, I've managed to resolve most of the issues. However, there is a persistent problem with certain files that have cased props, triggering Vue to generate an error message known as a & ...

The JSON payload was accidentally sent as "System.Collections.Hashtable" instead of the intended data

Using Powershell to dynamically generate a data payload for forwarding in a REST API Post Request has presented a challenge. Upon reception by the API, the payload is identified as System.Collections.Hashtable. It is evident that I am mishandling the form ...

using jquery, how can you send multiple parameters in an ajax request

Hello and welcome! I'm having trouble passing parameters through an ajax URL. I am attempting to send multiple data using the jQuery $.ajax method to my PHP script, but I can only pass a single data item when concatenating multiple data entries toget ...

Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered. Here's the link to the code snippet. <div ng-app="editer" ng-controller="myCtrl" ...

Invoking getJSON() repetitively within a loop inside another getJSON() call, within a new row specifically

Although I am not well-versed in JS, I have a feeling that I might be incorrect in the way I am handling this situation. The general idea here is to query the database for a list of items; then within the initial loop, create a row in the table by using th ...

Transfer information from an array to a Vue function

Having some difficulties passing data to the function myChart within the mounted section. As a beginner in vuejs, I'm struggling with identifying the issue. I am trying to pass data in labels and datasets, which are called from my function. Can anyone ...

Issue with parsing JSONP using jQuery's AJAX request

I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...

I've been endeavoring to compare the content IDs from two APIs using Jmeter

I am faced with a challenge where I have two APIs that contain the same content but have different URLs. My goal is to compare all the contents from both APIs using jmeter. So far, I have utilized the json extractor by setting the path as $..contentid and ...

Substituting identical values with different keys in a JSON object

Managing JSON key values can be tricky, especially when trying to replace them one at a time. The challenge arises when multiple keys have the same value in the JSON body. The goal is to update only one key value at a time, even if the values are identical ...