How can you retrieve an array of multiple property values from a collection of dynamic objects?

I am currently working with a dynamic JavaScript object array that has varying structures. For example:

var someJsonArray = [
  {point: 100, level: 3},
  {point: 100, level: 3},
  {point: 300, level: 6}
];

At times, it may have a different combination like:

var someJsonArray = [
      {discussion: 5, level: 3},
      {discussion: 4, level: 3},
      {discussion: 3, level: 6}
    ];

The goal is to extract a specific field from each object and create an array containing the values. For instance, from the first array, the result should be [[100, 3],[100, 3], [300, 6]].

If the array had static properties, I could easily loop through and push them into one array like this:

var arr = [];
for(var i=0; i<someJsonArray.length; i++) {
    arr.push(someJsonArray[i].id, someJsonArray[i].name);
}
console.log(arr)

However, since the array's structure is dynamic and can have any combination of properties (always two), I'm wondering how to achieve the same result. Any suggestions or workarounds for this challenge?

Answer №1

If you're looking for an alternative, consider using Object.keys:

let data = [
  {name: "John Doe", age: 30},
  {name: "Jane Smith", age: 25},
  {name: "Tom Brown", age: 35}
];
const result = data.map(Object.keys);
console.log(result);

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

Having trouble with ui-router: "$injector:modulerr" - it seems an error has occurred

I recently started the tutorial AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails by Thinkster, but encountered a problem. After creating an inline template, I ended up with a blank page and an error message $injector:modulerr with ...

Insert the variable into the specified div ID

I am looking to implement an incremental div id system to ensure all my ids are unique. This way, I can make use of jQuery effects to customize them individually. Let me know if you need further clarification on my query. div id ="name_$id" Perhaps I sh ...

When using NextJS, the dynamically generated HTML elements do not get affected by CSS repaint

Recently, I encountered an issue while working on a Next.js project involving the addition of an external script that uses vanilla JavaScript to dynamically create nodes. Despite importing global CSS at the top of my _app.js file, I noticed that the styles ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

I am looking to include query string variables within JSON key-value pairs

On my webpage, I have a .asp page using the following url: page.asp?id=33&album=ourcookout The page.asp file then calls a file.js script. Within the file.js script, there is a line located under a function that reads as follows: url: "post_file.php", M ...

The backbone module is experiencing formatting issues

I'm new to learning backbone.js. I've created the example below, but unfortunately, it's not functioning properly. Can someone please help me understand why? The goal is to simply display the name within my div element. (function($) { ...

Should we integrate a MongoDB database calculation app with a POST Controller in sails.js?

The primary function of the application interface is to provide variables that have been initially posted by the client, as well as any subsequent database calculations carried out in real time by a specialized engine. Is it possible to integrate this eng ...

Vue JS - Troubleshooting Checkbox Validation Error During Form Submission

When a user fills out my registration form, there is a checkbox to confirm acceptance of the terms and conditions. Currently, the validation error for this checkbox appears immediately upon hitting submit, even though the checkbox starts as unchecked. The ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...

The functionality of a Vue custom tooltip behaves strangely after clicking the button multiple times

I created this custom tooltip code that automatically closes after 2 seconds when a user clicks on a button, not just hovers over it. Initially, it works perfectly for the first two clicks, but then starts behaving strangely from the third click onwards. ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

Should one consider using the Express app.use() method within an asynchronous callback function?

Seeking advice on a recommended best practice. I recently developed an Express server that generates a JWT and sends it to the client whenever they hit an API endpoint. To maintain modularity, I separated the route handler into its own module and exporte ...

What is the main object used in a module in Node.js for global execution?

Node.js operates on the concept of local scope for each module, meaning variables defined within a module do not automatically become global unless explicitly exported. One question that arises is where a variable declared in a module file belongs in term ...

What is the process of importing a JSON data file and utilizing it within a React component?

As a beginner in React, I am struggling with the concepts of importing, exporting, and rendering components. I have a fakeData.json file within the same src/components folder as the component I want to render. Let's take a look at the structure: < ...

Troubles encountered with the search bar filter functionality, implementing JS/JQuery within a Laravel blade template

Currently, I have a blade template containing a search bar for filtering purposes. The issue I'm encountering is that the filtering functionality doesn't seem to work as expected after removing Angular from the page entirely. The page is set up ...

No invocation of useEffect

I am facing an issue with my React app at the moment. My high-level useEffect is not being triggered, although it works in another project with similar code. Typically, the useEffect should be called every time I make an HTTP request from the app, but noth ...

Utilizing React Router V4 to Render Dual Components on a Single Route

Looking for help with these routes <Route exact path={`/admin/caters/:id`} component={Cater} /> <Route exact path={'/admin/caters/create'} component={CreateCater} /> After visiting the first route, I see a cater with an ID display ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...