Generating a new array based on the keys found in a collection of objects

My array structure is quite complex with multiple objects containing different properties.

  let arr = [
    { id: 1, name: "tony", hatColor: "blue" },
    { id: 2, name: "larry", hatColor: "red" },
    { id: 3, name: "stuart", hatColor: "green" },
  ];

I am looking to extract specific arrays for each key in the main array - one for ids, one for names, and one for hat colors.

idArr = [1, 2, 3];
nameArr = [tony, larry, stuart];
hatColorArr = [blue, red, green];

However, the exact structure of the array of objects may vary as it is generated dynamically.

My attempt to achieve this using nested loops and mapping has resulted in an array of undefined values. I am hoping for a more efficient way to accomplish this without hardcoding numerous if statements.

Any help or suggestions would be greatly appreciated. Thank you.

Answer №1

Utilize the Array.map method to extract the property values from each element within an array.

let arr=[{id:1,name:"tony",hatColor:"blue"},{id:2,name:"larry",hatColor:"red"},{id:3,name:"stuart",hatColor:"green"];

function extractPropertyValues(objs, prop){
    return objs.map(e => e[prop])
}

idArr = extractPropertyValues(arr, 'id');
nameArr = extractPropertyValues(arr, 'name');
hatColorArr = extractPropertyValues(arr, 'hatColor');
console.log(idArr, nameArr, hatColorArr)

If the intention is to automatically create these arrays, one can achieve this by accessing the properties of each object in the array, obtaining their values, and then storing them in a new object.

let arr=[{id:1,name:"tony",hatColor:"blue"},{id:2,name:"larry",hatColor:"red"},{id:3,name:"stuart",hatColor:"green"];

function extractPropertyValues(objs, prop) {
  return objs.map(e => e[prop])
}

const properties = [...new Set(arr.reduce((a,b) => (a.push(Object.keys(b)), a), []).flat())]

const result = properties.reduce((a,b) => (a[b] = extractPropertyValues(arr, b), a), {})

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

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

Attempting to save the result of a fetch call into a variable for the purpose of rendering it as a list in a

I'm attempting to fetch the top 5 NFT collections based on volume and display them in a table format. However, I'm facing an issue where the data is not being mapped correctly and when I click the "get" button, all content on the webpage disappea ...

What could be the reason for the malfunctioning dropdown menu in my navigation bar upon clicking it?

After spending hours practicing creating a navbar using Bootstrap 3.3.7, I've hit a roadblock - the dropdown is not working when clicked on. It's frustrating because I have double-checked all my scripts and ensured that I have the latest version ...

Develop a JavaScript library for use in the npm ecosystem

I have developed a minimalist JavaScript library that includes common functions: !!window.JsUtils || (window.JsUtils = {}); JsUtils = (function () { "use strict"; return { randomHex: function (len) { var maxlen = 8; ...

Tips for replacing the nested array object in JavaScript

I am seeking guidance on how to merge and overwrite the existing object values in a nested array using JavaScript. In the scenario presented below, I want to merge the 'other_obj' with the 'obj' that has an id of "zen", overwriting the ...

Tips for transmitting an array of Objects to AngularJS

Summary I'm curious about how I can successfully send the following array of objects from NodeJS to an AngularJS app. var players = [ Footer: { username: 'Footer', hp: 200, exp: 1 }, Barter: { username: 'Barter', hp: 200, e ...

Transmitted only JSON data instead of using multiform data with jQuery Ajax

When I use jQuery Ajax to send a JSON object, it ends up being interpreted as 'multiform' instead of pure JSON. How can I make sure my request is sent as a pure JSON object and not multiform? var demo = new Array("One", "Two", "Three"); $.ajax ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

During the for loop, a string variable with the prefix "undefined" is

I'm currently working with a drop-down menu where I use the .Change() function to trigger a specific action. This action involves obtaining data using the getJSON method and then creating an array string for an mp3 file based on that data. The code b ...

In AngularJS, enhance pagination loading by appending a $resource queried array to the end of another

I'm currently working on implementing a loading feature for my Angular application. The goal is to preload page 3 when a user navigates to page 2. Utilizing $resource, I'm querying the Posts resource using Post.query(). By calling Post.query({pa ...

Issue with alert not being triggered in browser when using HTML and JavaScript function

Just starting out with HTML and Javascript! I'm working on a simple program where users can input a card number, and the browser should indicate whether it is valid (between 13-16 digits) or not. The website looks great, but I'm not getting an ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...

Attempting to retrieve user information from Blockstack on a web browser

Currently developing a web application integrating Blockstack and encountering challenges with Javascript implementation and understanding how to effectively use Blockstack in the browser. My issue arises when retrieving the Blockstack user's ID or u ...

Arranging based on attribute data

I'm currently working on organizing a collection of divs that have unique custom data attributes which I aim to sort based on user selection. For instance, if 'followers' is chosen, the .box elements will be arranged according to their data- ...

Instructions for displaying typed chat messages on the screen using socket.io and node.js

I am currently developing a chat application using socket.io and node.js. I have successfully connected the server and both the socket.io and client-side socket.io are also connected. However, when I type a message on the localhost page and hit enter, noth ...

jQuery Validation is not functioning correctly

I am facing an issue with implementing jQuery.Validation. I have written a script and included all JS files below, but for some unknown reason, the validation always returns that the form is valid. Below is the JavaScript code I am using: $(document).rea ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Using a for loop to scrape data from websites in Python

I've been working on a small project that involves web scraping Google search results using a list of keywords. I set up a nested for loop to scrape the data, but I'm running into an issue where the loop is only giving me results for the last key ...

Having trouble with a 400 Bad Request error when sending a POST request from my Vue application to my Rails API

Currently delving into the world of Rails and Vue, I decided to take on a small project involving a basic Rails API and Vue app to practice making GET and POST requests from my Vue app to the Rails API. While GET requests are working smoothly, I'm enc ...