What is the best method for iterating through JSON data and extracting a specific key-value pair?

Having just started learning JavaScript, I'm a bit confused on how to retrieve a specific key value from a JSON file:

var me = {"fcolors": ["blue", "green", "whitesmoke"],"fire": ["pink", "grey", "red"]};

I am interested in extracting only the fcolour values

fcolour = [];
for (var key in me) {
    if (me[key] instanceof Array) {
        for (var i = 0; i < me[key].length; i++) {
            console.log();
            fcolour.push(me[key][i])
        }
    }
}

The desired result should be

fcolour=["blue", "green", "whitesmoke"]

Many thanks in advance and any feedback is welcomed.....

Answer №1

If your JSON does not contain an array of fcolors, you do not need to loop through to get its value:

Simply accessing me.fcolors will provide you with ["blue", "green", "whitesmoke"]

Check out this example on Plunker

In case of multiple objects:

var data = [{
  "fcolors": ["blue", "green", "whitesmoke"],
  "fire": ["pink", "grey", "red"]
}, {
  "fcolors": ["red", "white", "yellow"],
  "fire": ["black", "gray", "pink"]
}];

var fcolors = [];

for (var i = 0; i < data.length; i++) {
  if (data[i].hasOwnProperty('fcolors')) {
    fcolors.push(data[i].fcolors);
  }
}

console.log(fcolors);

fcolors now holds an array

View the demonstration on Plunker

Answer №2

What is the reason for iterating through JSON when you have direct access to the specified JSON as

me.fcolors; // This will return ["blue", "green", "whitesmoke"]

Answer №3

To retrieve the desired value from a flat object array, you can utilize the following code snippet.

var data = {colors: [...], shapes: [...]};    

if (data.hasOwnProperty('colors')) {
    var colors = data.colors;
}

If there are multiple similar objects within the array, you can extract all values using this method.

var data = [
    {colors: [...], shapes: [...]},
    {colors: [...], shapes: [...]},
    {colors: [...], shapes: [...]}
];

var colors = [];

for (var i = 0; i < data.length; i++) {
    var currentObj = data[i];

    if (currentObj.hasOwnProperty('colors')) {
        colors.push(currentObj.colors);
    }
}

Once executed, colors will be transformed into a multidimensional array.

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

Saving the previous component's DOM in a React application

Understanding the Root.js File const Root = () => ( <HashRouter> <div> <Route exact path="/" component={Main}/> <Route path="/main/:page" component={Main}/> <Route path="/detail ...

Customizing Checkbox using CSS (additional assistance required)

I am currently working on implementing Checkbox Four with a custom design. You can check out the example I found on this website: My goal is to enhance this checkbox by incorporating red colored text 'N' when it's unchecked, and blue colore ...

Using a PHP WordPress Loop, eliminate the comma following the final object in the Schema array

My Google Schema Markup for a "Product" includes a loop that displays "Reviews". Below is an excerpt of the code: "review": [ <?php $args = array( 'post_type' => 'my_reviews', & ...

Unable to establish header once it has been sent

Here is my code: function handleToken(response, error, token) { if (error) { console.log("Error retrieving access token: ", error.message); response.writeHead(200, {"Content-Type": "text/html"}); response.write('<p>ERROR: ' + ...

If the console is not open, console.log will not update

When I press the reset button on my simple function, I expect to see the FIRST console.log in the console right away, displaying an array with 5 objects. After 5 seconds, the SECOND console.log should be displayed with an empty array. Everything seems to w ...

Anticipated an array but received something else (JSON) - AngularJS Error

Currently, I am immersing myself in Angular1 with the help of Adam Freeman's "Pro AngularJS" book. However, I have encountered a hurdle while trying to build a DeployD app as outlined in chapters 6-8. It appears that my code is having trouble reading ...

retrieve data from JSON file

function retrieveDataFromProfiles(){ const fs = require('fs') fs.readFile('src/data/profileInfo.json', function(error, data){ if(error){ alert(error); } var profileData = JSON.parse(data); //retrieves the JSON data of ...

Vue Pinia ensures that reactive state is only updated once, preventing unnecessary updates

In my Vue application, the structure is as follows: App.vue -GroupWrapper --GroupListing -PeopleWrapper --PeopleListing -ConversationWrapper Within my user store that utilizes Pinia, I primarily call user.findChats() in the App.vue component. Code snippe ...

Creating a multitude of cubes by iterating through the pixel color data of getImageData in Three.js

Using a simple 3x3.png file to extract color/opacity data from, where each of the 9 pixels represents a different color/opacity level. The .png is supposed to be loaded onto an off-screen canvas, following which the 9 cubes are drawn in a 3x3 grid pattern ...

What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format: queryObj = {}; // main object passed to mongodb for queries The code snippet below is causing an error: queryObj[inObj.row]['$ ...

Dynamic menu that showcases chosen options along with an option to "Add more"

Creating a select drop-down menu that displays the selected results off to the side in a span with "Results" added before it (similar to a label in a form input). Beneath the select, there is an "Add another" button. When clicked, it adds another "Results ...

JavaScript is providing HTML output instead of JSON results

Recently, I have been facing an issue with connecting to bitbucket and collecting the commits. The code snippet that I used is as follows: import fetch from 'node-fetch'; async function fetchData(){ await fetch('https://bitbucketexam ...

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

Ways to merge two select options in a form

I'm attempting to merge the selections from two dropdown menus in a form into one variable before submitting the form. Here is an overview of my code: In new.html.erb (for RoR): <%= form_for :character, url: characters_path, method: :post do |f| ...

What is the process for removing a mesh that has been uploaded using a function and then added to an Object3D?

// Defining variables for 3 obj models: cushion, backrest, and frame, and a group variable chair01 to include all 3 obj models var cushion; var backrest; var frame; var chair01 = new THREE.Object3D(); ...

What is the method for ensuring that the state and component have identical values?

Currently, I am diving into the world of UI design using the React library. However, I seem to be encountering some issues with my code. handleIncrement = () => { this.setState({ ...this.state, quantity: this.state.quantity + 1 }) ...

What is the best way to extract specific values from a list within a set range?

I been playing around with a list y = [6,7,3,9,5,4,1,0,9,2,10,16,13], and I thought of coding a function where I could manually input (min,max) values, and I want this function to generate a list of values that fall within the range of the min and max va ...

Struggling with ThreeJS bufferGeometry position attribute not refreshing after applying translation

Leveraging STLLoader, I successfully loaded an stl file onto a threeJS scene and obtained a BufferGeometry. Following that, I utilized myMesh.position.set(x, y, z) myMesh.rotation.setFromQuaternion(quaternion, 'XYZ'); to manipulate the geome ...

Instructions on utilizing Array.fill() with a single object but creating distinct copies for each index

When creating an array and populating it using the fill method, I noticed that changing array1[0].foo also changes all other objects in the array. const array1 = Array(2).fill({ foo: null }) array1[0].foo = 'bar' // [ { foo: 'bar' }, { ...

"Encountered an error while trying to locate the view" in a simple Express.js application

Embarking on the journey to learn Express.js, I decided to create a simple Express app. The structure of my app.js is as follows: var express = require('express'); var app = express(); app.configure(function(){ app.set('view engine&ap ...