What is the best way to obtain a list of all product names?

I need to extract only the names of the objects (cat, dog, bird)

/// Names of objects I want to retrieve ///

 var storage = [
    {cat: {name: "Garfield", count: 3443, price: 1000}},
    {bird: {name: "Eagle", count: 4042, price: 3000}},
    {dog: {name: "Rex", count: 1488, price: 2000}}
    ];

    function  extractObjectNames(storage) {
        var keys = [];
        for(var key in storage) {
            keys.push(key);
            if(typeof storage[key] === "object") {
                var subkeys = extractObjectNames(storage[key]);
                keys = keys.concat(subkeys.map(function(subkey) {
                    return key + "." + subkey;
                }));
            }
        }
        console.log(keys);
        return keys;
    }
    extractObjectNames(storage);

Answer №1

If you want to extract the first key of objects in an array, you can achieve this by utilizing Array#map to iterate over the array and retrieve the property using Object.values.

function  extractFirstKeys(data) {
    return data.map(obj => Object.values(obj)[0].name);
}

var data = [{ cat: { name: "Garfield", count: 3443, price: 1000 } }, { bird: { name: "Eagle", count: 4042, price: 3000 } }, { dog: { name: "Rex", count: 1488, price: 2000 } }];

console.log(extractFirstKeys(data));

Answer №2

let animals = [
    {lion: {name: "Simba", count: 1000, price: 5000}},
    {elephant: {name: "Dumbo", count: 2000, price: 8000}},
    {zebra: {name: "Marty", count: 500, price: 3000}}
    ];
let species = []; 
animals.map(function(animal){
  species.push(Object.keys(animal)[0]);
})
console.log(species);

Answer №3

Using a basic for...in loop

var counter = 0;
var list = []
var data = [
    {cat: {name: "Garfield", count: 3443, price: 1000}},
    {bird: {name: "Eagle", count: 4042, price: 3000}},
    {dog: {name: "Rex", count: 1488, price: 2000}}
    ];

for(counter in data) {
      list.push(Object.values(data[counter])[0].name)
}
console.log(list)

Answer №4

Consider using this code snippet for situations where each storage object contains multiple products:

let productList = [];
storage.forEach((object) => {productList.push(...Object.keys(object))})
console.log(productList)

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

Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS. module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'bab ...

What is the best way to use selenium for iterating through multiple pages on a website?

Recently, I've been attempting to create a Python script to scrape a specific website for a list of all URLs. The website in question is . The main challenge I've encountered is that the website utilizes Javascript for navigation, making it diff ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

Is there a way to retrieve the properties of another function within the same component?

I am trying to place NumberFormat inside OutlinedInput and I also need different properties for the format of NumberFormat. (There will be a select window that defines which format property to use). This is what I have: import OutlinedInput from "@ma ...

Ways to efficiently transmit pre-designed HTML components from a WebMethod to jQuery

I'm currently working on implementing infinite scrolling on my ASP.NET C# Website. In the past, I used a somewhat cumbersome method involving the ListView Control to achieve lazy scrolling, but I'm looking for a more efficient solution this time. ...

PhantomJS: Saving SVG for Future Use

I am attempting to save an SVG file from a sample testpage using PhantomJS. I have successfully navigated to the testpage, but I am unsure of how to locate and save the SVG element. Below is my current approach and where I am encountering difficulties. V ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

A guide on breaking down the ID passed from the backend into three segments using React JS

I pulled the data from the backend in this manner. https://i.stack.imgur.com/vMzRL.png However, I now require splitting this ID into three separate parts as shown here. https://i.stack.imgur.com/iy7ED.png Is there a way to achieve this using react? Bel ...

What is the best way to display input data (with names and values) in a textarea field

I'm currently working on a project that requires the value of a textarea to be updated whenever one of the input values in the same form is changed. Here is the HTML code: <form id="form" action="" method=""> <textarea readonly class="overv ...

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...

What is the best way to implement window.load in React Native?

I'm encountering an issue with a simple button on my page in Expo/React Native. When I try to navigate to a new page using window.open upon clicking the button, I receive an error message saying "undefined is not a function." Although I am utilizing ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...

Updating controller variables when the route changes in AngularJS

I'm new to the AngularJS scene and I've encountered a challenge. My goal is to have the selected tab change dynamically based on the URL changes. Here's my JavaScript code: app.config(function($routeProvider, $locationProvider){ $rou ...

The array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...

Utilize anonymous functions to reassign the button click event - JQuery

I'm dealing with a situation where I have 5 HTML buttons, each with a click event listener attached to it in the form of an anonymous function. For example: $('#button1').click(function(){ //some code }); At a certain poin ...

Why is my md-button in Angular Material displaying as full-width?

Just a quick question, I created a simple page to experiment with Angular Material. On medium-sized devices, there is a button that toggles the side navigation, but for some reason, it expands to full width. There's no CSS or Material directives causi ...

Using React JS to automatically execute an event based on a specific state value

Is there a way to initiate an action from a main component when the child component's state reaches a specific value? Let's consider a scenario where I have a Parent component and a Child component, with the parent's state containing active ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

Shift div position when clicked and employ jQuery animations

I have been attempting to add animation to a DIV element by using jQuery. The goal is to move the DIV from the center to the left when it is clicked, but I am encountering some issues. The parent div has a position of "relative", and my initial idea was to ...