Generate two arrays in JavaScript using the information stored in an object

I am in need of a loop that can generate 2 arrays based on some data...

To start, I create the following 2 arrays:

namelist = [];
countList = [];


{
    "id": "665",
    "name": "primary",
    "contents": {
        "692": {
            "id": "692",
             "title": "title 1",
            "info": {
                "quantity": 8
            }
        },
        "757": {
            "id": "757",
            "title": "title 2",
            "info": {
                "quantity": 15 
            }
        }
    }
}

In this scenario, the intended outcome would be:

For namelist:

['title 1', 'title 2']

And for countList:

[8, 15]

How should I approach achieving this?

Answer №1

var nameList = [];
var countList = [];

var myObj = 
{
    "id": "622",
    "name": "main",
    "sub": {
        "637": {
            "id": "637",
            "name": "name 1",
            "stats": {
                "count": 5
            }
        },
        "638": {
            "id": "638",
            "name": "name 2",
            "stats": {
                "count": 10 
            }
        }
    }
};



for(var key in myObj.sub){
    nameList.push(myObj.sub[key].name);
    countList.push(myObj.sub[key].stats.count);
}

console.log(nameList);
console.log(countList);

Answer №2

Iterating through the keys in the sub object, we are populating two arrays: nameList with the names from each key's value and countList with the count from each key's stats property.

Answer №3

When you need to iterate through object properties, using <code>Object.keys
can be very helpful. Here's an example specific to your object:

var namelist = [],
  countList = [],
  obj = {
    "id": "622",
    "name": "main",
    "sub": {
      "637": {
        "id": "637",
        "name": "name 1",
        "stats": {
          "count": 5
        }
      },
      "638": {
        "id": "638",
        "name": "name 2",
        "stats": {
          "count": 10
        }
      }
    }
  };

Object.keys(obj.sub).forEach(function(item) {
    namelist.push(obj.sub[item].name);
    countList.push(obj.sub[item].stats.count);
});

console.log(namelist, countList);

If you'd like to see this code in action, check out this working example: https://jsfiddle.net/ry0zqweL/

This is just one way to approach the problem - there are many ways to optimize and enhance this solution.

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

Techniques for manipulating multiple circles with JavaScript

After creating a series of circles with d3, I successfully implemented the functionality to drag individual circles and track their positions. var width= 800; var height=600; svg= d3.select("body").select(".div1").append("svg") ...

How to focus on a dynamically changing input box in Vue

In my form, users can input an email address and click a plus button to add another input box for a new email address. These input boxes are created by iterating over an array, so when the user clicks on the plus icon, a new entry is added to the array. W ...

What is the best method for comparing two elements effectively in JavaScript?

Check out this code snippet that ensures txtKeyword input is focused when a key is pressed by the user. var txtKeyword = document.getElementById("txtKeyword"); ... document.addEventListener("keypress", function(event) { if(event.src ...

Retrieve the Corresponding Content Inside the Div Element

I have a div with text that needs to be matched with comma-separated values: <div class="val"> This is paragraph 1 </div> <div class="val"> This is paragraph 2 </div> Using an Ajax call, I retrieve the ...

Encountering a null value in my list component variable, resulting in an error when attempting to access properties (specifically 'date')

My list card component showcases various devices with details such as their name, brand, image, and booked status (including how long they are booked for if applicable), all sourced from a Json file. I am facing two challenges: I am looking for a more eff ...

Generating and saving a text file in a React Native application

Is there a way to convert a string into a text file within the client application and then download it directly onto a phone? If so, how can this be achieved? ...

Getting rid of the scrollbar in Internet Explorer

Instead of just removing the scrollbar, I want to ensure that scrolling capabilities remain intact. This is important because I want to create a 'slide show' effect on the website where users can click 'next' and scroll through content ...

XCODE encountered an issue while attempting to open the input file located at '/Users/name/Desktop/test/appname/node_modules/react-native-compressor/ios/Video/Compressor-Bridging-Header.h'

Encountering an issue while running my project in XCode. I recently added the react-native-compressor package by following the steps mentioned in the installation guide When attempting to run the project in XCode, the error below occurs: <unknown> ...

Tips for dynamically inserting a tabbed element into a list using AngularJS

I am trying to dynamically add elements with tabs in the list, but I encounter a problem where the device info gets overridden from the last user. You can see the issue here: https://i.sstatic.net/O1uXK.jpg This is how my Tabs item looks like in HTML: & ...

Transform the size and convert an object from a picture into text based on the user's scrolling

I've been intrigued by the scrolling effects used on websites like Google SketchUp and Google Plus. It's fascinating how elements can transform as you scroll down the page. For example, on Google SketchUp's site, the banner starts off integr ...

What is the solution to eliminating the MultiValueDictKey error when making an AJAX get request?

When handling multiple divs on a web page, each containing a form, I encountered the need to utilize AJAX Get functionality. The goal was to pass the text entered into a form along with the ID of the corresponding div to a Django view for storage in a data ...

Adding variable data from an external file into Google Maps V3

Is it possible to use includes in Java for Google Maps like you can in PHP? Currently, I have code that assigns colors to polygons. var lineColor = { "Tornado Warning": "#FF0000", "Severe Thunderstorm Warning": "#FFFF33", "Flash Fl ...

PHP array input with spaces in between elements on the same line, without any new line

As a newcomer in PHP, I am looking to receive an array input from the user in a single line with only one space in between each element, like 5 6 2 1 4. However, my current code is taking inputs like: 5 6 2 1 4 and then providing the desired outp ...

Comparing values in an array with PHP

Hello everyone, I could really use your assistance. Let's consider a scenario where I have an array. $arr = array( 1 => array( key1 => something, key2 => something, key3 => something, testkey => 3 ...

The information retrieved from the API call did not meet my expectations; instead, it returned as undefined

In my development project, I have organized my functions in a file called PostApi.js. In another file, Posts.js, I make the call to these functions. However, when using api.getPosts() and data in the Posts.js file, I encounter an issue where it returns un ...

Storing a function in local storage using Javascript

Is there a way to save this information in local storage, or is there an alternative method for storing it? $('#pass_to_score').on('click',function(){ var compressed = function(){ $('.whole_wrap_of_editcriteria').css(&ap ...

Having trouble with a basic image carousel function?

Currently in the process of developing a basic image carousel for a practice website I'm working on. I've been following this tutorial on YouTube. At the 7:10 mark, the tutorial demonstrates the specific function that I need help with. The tuto ...

Unexpected result when trying to return a value from a recursive function

Attempting to solve the problem of calculating the number of ways a number can be decoded, with 1 as a, 3 as c, and 26 as z. The function seems to calculate the correct count, but for some reason only returns undefined. It appears that the recursive calls ...

Custom Script for Single Tumblr Entry

While I know it's possible to edit the HTML/AngularJS for the overall posts on a Tumblr blog homepage, I'm wondering if there is a way to insert a custom <script>...</script> into individual posts. I have some specific JavaScript task ...

Tips for designing a hyperlink insertion modal while preserving text selection

I am working on a React website that utilizes Slate-React () for creating a rich text input field. Currently, Slate uses the browser's prompt() function to add hyperlinks to selected text. However, I need to customize the styling of the prompt modal a ...