Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to improve my current solution would be greatly appreciated. The keys within the objects are dynamic and not always consistent.

The desired output based on my example should be: [ "stuff", "type", "misc", "something" ]

const items = [{
    name: "Joe",
    occupied: "no",
    mobile: "yes",
    treatment: "no",
    date: "29-03-2020",
    age: "15",
    stuff: ["A", "B", "C"],
    type: ["1", "2"]
  },
  {
    name: "Jack",
    occupied: "yes",
    mobile: "no",
    treatment: "no",
    date: "02-03-2020",
    age: "20",
    stuff: ["A", "B", "C", "D", "E"],
    type: ["8", "6"],
    misc: ["otherStuff", "someStuff"]
  },
  {
    name: "Jane",
    occupied: "no",
    mobile: "yes",
    treatment: "yes",
    date: "15-02-2020",
    age: "28",
    stuff: ["C", "D", "E"],
    type: ["4", "7"],
    something: ["xxx", "ccc"]
  }
];
function getKeysWithArrayValues(myArray) {
  const result = [];
  myArray.forEach(item => Object.entries(item).forEach(itm => itm.filter(Array.isArray).forEach(x => result.push(itm.slice(0, 1))));
  
  return flatArray(result)
};

function flatArray(array) {
  return array.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatArray(val)) : acc.concat(val), []);
};
const ttt = getKeysWithArrayValues(items);
const flat = Array.from(new Set(ttt))
console.log(flat);

Answer №1

Here is a possible solution that may assist you. The algorithm outlined here is quite straightforward, and I believe there is no necessity for a lengthy explanation. Essentially, we iterate through an array using the reduce method and construct a new array consisting only of keys that meet our specified criteria.

The check Array.isArray(rec[key]) verifies whether the value is an array.

The condition acc.indexOf(key) < 0 confirms if the key has not already been added to the resulting array in any previous steps.

const modifiedArray = items
  .reduce((acc, rec) => {
    return [...acc, ...Object.keys(rec).filter(key => Array.isArray(rec[key]) && acc.indexOf(key) < 0)]
  }, [])

Answer №2

If you want to extract unique keys from objects, one approach is to utilize a Set.

const
    data = [{ name: "Alice", age: 25, city: "New York" }, { name: "Bob", age: 30, city: "Los Angeles" }, { name: "Charlie", age: 35, city: "Chicago" }],
    uniqueKeys = Array.from(
         new Set(data.flatMap(obj => Object.keys(obj)))
    );

console.log(uniqueKeys);

Answer №3

Utilize the flatMap method in order to loop through each object's keys and generate an array of keys that meet the condition of containing an array as its value:

const items=[{name:"Joe",occupied:"no",mobile:"yes",treatment:"no",date:"29-03-2020",age:"15",stuff:["A","B","C"],type:["1","2"]},{name:"Jack",occupied:"yes",mobile:"no",treatment:"no",date:"02-03-2020",age:"20",stuff:["A","B","C","D","E"],type:["8","6"],misc:["otherStuff","someStuff"]},{name:"Jane",occupied:"no",mobile:"yes",treatment:"yes",date:"15-02-2020",age:"28",stuff:["C","D","E"],type:["4","7"],something:["xxx","ccc"]}];
  
const keysWithArrays = new Set(
  items.flatMap(
    item => Object.keys(item).filter(key => Array.isArray(item[key]))
  )
);
console.log([...keysWithArrays]);

Answer №4

To determine if a value is an array, you can utilize the set method along with Array.isArray().

let myArray = new Array();    const elements = [{name: "Joe",occupied: "no",mobile: "yes",treatment: "no",date: "29-03-2020",age: "15",stuff: ["A", "B", "C"],type: ["1", "2"]},{name: "Jack",occupied: "yes",mobile: "no",treatment: "no",date: "02-03-2020",age: "20",stuff: ["A", "B", "C", "D", "E"],type: ["8", "6"],misc: ["otherStuff", "someStuff"]
}, {name: "Jane",occupied: "no",mobile: "yes",treatment: "yes",date: "15-02-2020",age: "28",stuff: ["C", "D", "E"],type: ["4", "7"],something: ["xxx", "ccc"]}];

elements.forEach((object)=> Object.keys(object).forEach( property=>{if(Array.isArray(object[property])) 
myArray.add(property)})); console.log(Array.from(myArray));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №5

Here is an alternative method using Object.fromEntries, flatMap, and filter.

const items = [
  {
    name: "Joe",
    occupied: "no",
    mobile: "yes",
    treatment: "no",
    date: "29-03-2020",
    age: "15",
    stuff: ["A", "B", "C"],
    type: ["1", "2"]
  },
  {
    name: "Jack",
    occupied: "yes",
    mobile: "no",
    treatment: "no",
    date: "02-03-2020",
    age: "20",
    stuff: ["A", "B", "C", "D", "E"],
    type: ["8", "6"],
    misc: ["otherStuff", "someStuff"]
  },
  {
    name: "Jane",
    occupied: "no",
    mobile: "yes",
    treatment: "yes",
    date: "15-02-2020",
    age: "28",
    stuff: ["C", "D", "E"],
    type: ["4", "7"],
    something: ["xxx", "ccc"]
  }
];

const keys = Object.keys(
  Object.fromEntries(
    items.flatMap(item =>
      Object.entries(item).filter(([, value]) => Array.isArray(value))
    )
  )
);

console.log(keys);

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

Sockets causing a blockage in the Express server

Encountering an issue while setting up an express server with Sockets (using the socketcluster-server module). After sending around 20 http requests, the express server gets blocked, leading to the Sockets (client) reporting a connection depletion. Has an ...

Searching in a PHP 4 level deep multidimensional associative array for a specific value

Hey everyone! I have this multidimensional associative array and I'm looking to search within it. public static function userAccessArray() { return array( array( 'title' => 'General', 'ac ...

Is it possible that Pandas is unable to generate a CSV file?

Having trouble saving websockets data to CSV files. Despite trying various methods such as running Visual Studio Code as admin and moving the folder location, no file is being created. There are no error messages either, and unfortunately, I couldn't ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...

React Router updates the URL path without actually rendering the content of the second page

I'm having an issue with my React app where the address changes correctly in the search bar, but the page is not loading. Here is my code: import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; i ...

Angular custom window injection

Currently, I am working on an Angular application that is housed within an Android WebView. To facilitate communication with my Android application, I have made an object accessible at the window level: window.MyAndroidApp This object contains various me ...

Exploring JSON object parsing on Android

When I make a call to the server, its response is based on a JSON object. Although I am familiar with parsing JSON objects, this particular response seems unusual to me. The server's response is as follows: {"body":"Not Available!","clazz":"SoccerMat ...

Struggling to display AJAX GET results on my webpage, although they are visible in the Google Element Inspector

I'm working on a basic invoice page where I need to populate a dropdown box from my MySQL database. The issue I'm facing is that when I select an item, the description box doesn't get prepopulated as expected. I've checked in the networ ...

Format for exchanging tabular data

Background: In my Asp.Net (C#) web application, I have been utilizing CSV as the data exchange format for bulk uploads. So far, the CSV file has been successfully serving its purpose. However, upon further research into different cultures, we have encount ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

Creating uniform URLs using MVC .NET routing: a guide

While using ASP.Net MVC 5 in .NET Framework 4.8, I am constantly facing a 404 error due to inconsistent URL generation. For instance, when including the _PageNav.chstml partial at the top of each page and adding @Url.Action("Index", new { controller = "Hom ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Selenium encountered an error when trying to execute the 'querySelector' function on the document. The selector provided, my_selector, is not recognized as a valid selector

Whenever I run this code: document.querySelector(my_selector) using selenium, an error is thrown: Failed to execute 'querySelector' on 'Document' my_selector is not a valid selector my_selector is definitely a valid selector that func ...

Beginning your journey with Mock server and Grunt

Although I have gone through the documentation available at , I am still struggling to get the mockserver up and running despite spending hours on following the instructions provided in the guide. Could someone please outline the precise steps or identify ...

How can I use jQuery to retrieve the total number of elements in a dropdown list?

I am working with a dropdown list that looks like this: <select id="ddlProjects"> <option value="315">resproject</option> <option value="320" style-"display:inline">newheavn</option> <option value="395" style="di ...

Obtaining exchange rate data in JSON format from fixer.io and displaying it in

Looking to extract the current USD to EUR exchange rate from fixer.io and display it as a single line in an HTML file, with the USD value represented using commas instead of periods. Any assistance would be greatly appreciated! Find the link here: { ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

Use JavaScript to dynamically populate dropdown list options with array elements

I attempted to populate a dropdown list with array elements using javascript, but I encountered issues. I referred to the following links for assistance: JavaScript - populate drop down list with array use a javascript array to fill up a drop down se ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...