Retrieve the keys from the initial object within an array of objects

I am looking to extract a list of unique keys from an array of objects.

arr =[
   {id: 1, desc: "", name: "", objectives: Array(3), …},
   {id: 2, desc: "", name: "", objectives: Array(3), …},
   {id: 3, desc: "", name: "", objectives: Array(3), …},
   {id: 4, desc: "", name: "", objectives: Array(3), …},
]

The desired output should be [id, desc, name, objectives]. I have attempted the following approaches:

Object.keys(arr)[0]
// output [{id: 1, desc: "", name: "", objectives: Array(3), …}]

arr.flatMap(Object.key)
// output ["id", "desc", "name", "objectives", "id", "desc", "name", "objectives", "id", "desc", "name", "objectives", "id", "desc", "name", "objectives"]

I apologize if I might have overlooked the answer to this while searching on SO. Any assistance would be greatly appreciated.

Answer №1

If you want to remove duplicate elements, one approach is to utilize a Set:

const array = [
   {id: 1, desc: "", name: "", objectives: []},
   {id: 2, desc: "", name: "", objectives: []},
   {id: 3, desc: "", name: "", objectives: []},
   {id: 4, desc: "", name: "", objectives: []},
];

const uniqueKeys = [...new Set(array.flatMap(Object.keys))];

console.log(uniqueKeys);

Answer №2

Here is a functioning code snippet:

data = [
   {id: 1, description: "", title: "", tasks: Array(3)},
   {id: 2, description: "", title: "", tasks: Array(3)},
   {id: 3, description: "", title: "", tasks: Array(3)},
   {id: 4, description: "", title: "", tasks: Array(3)},
];

keysArray = [];
Object.keys(data).forEach(keys => {
    Object.keys(data[keys]).forEach(key => {
    keysArray.push(key);
  });
})
console.log(keysArray);

Answer №3

    const array =[
      {id: 1, desc: "", name: "", objectives: Array(3), …},
      {id: 2, desc: "", name: "", objectives: Array(3), …},
      {id: 3, desc: "", name: "", objectives: Array(3), …},
      {id: 4, desc: "", name: "", objectives: Array(3), …},
    ];

    let filterDistinct = function(array, key) {
       let seenValues = [];
       let uniqueObjects = [];
       for(i = 0; i < array.length; i++) {
         // If this value is new and distinct, add it to our filtered list.
         if(!seenValues.includes(array[i][key]) {
            uniqueObjects.push(array[i]);
         }
         // Add this value to our seen values.
         seenValues.push(array[i][key]);
       }
       return uniqueObjects;
    }

    // Sample usage, filter by description
    let filteredData = filterDistinct(array, "desc");

    // Sample usage, filter by id
    let filteredDataById = filterDistinct(array, "id");

This approach should effectively filter the array based on the specified key. Keep in mind, if any of the values in your object are nested objects, you will need to perform a deeper comparison to ensure accurate filtering.

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

Generating requests using ExpressJS

Is it possible to send a POST request using a GET action? Although everything seems to be working fine, the "TOKEN" does not appear after the post. I am puzzled as to why this is happening. const request = require('request'); exports.g ...

angular-library.js:6 Uncaught TypeError: Unable to access the 'toLowerCase' property of an undefined value

$scope.searchCat = function(){ $scope.searchArray = []; const searchField = document.querySelector('#search input[type="search"]'); if(searchField){ $scope.searchTerm = searchField.value.toLo ...

Is there a way to display an alert using JavaScript that only appears once per day?

I've created a website that displays an alert to the user upon logging in. Currently, the alert is shown each time the user logs in, but I'm looking to make it display only once per day at initial page loading. How can I achieve this? Below i ...

Lack of Typescript 2.1 and Angular 2 type definitions with browserify

` vscode 1.7 Typescript 2.1.1 Angular 2 latest package.json "dependencies": { "@angular/common": "^2.2.4", "@angular/compiler": "^2.2.4", "@angular/core": "^2.2.4", "@angular/platform-browser": "^2.2.4", "@angular/platform-browser-dyna ...

Add a sub-modal window inside a separate container

Is there a way to attach this modal to an external div? The current setup involves nesting it within a container that has a fixed height. I'm looking to move it outside of that container. Here is the JavaScript code for the modal: client.fetchQuery ...

Fixing the Jquery Clone Bug

Recently, I came across a jQuery clone plugin that is designed to fix the values of cloned textarea and select elements. This code snippet showcases how it works: (function (original) { jQuery.fn.clone = function () { var result = ori ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

The $emit method in Vue seems to be ineffective when used on the parent component, yet it functions properly when used on the

I have a component called "register" which contains an event listener @submit.prevent inside the template, and I am using $emit to send the data. When I console.log within the method of the component itself, it works fine. However, when I try to access the ...

I am encountering an issue where body-parser is not functioning properly with typescript. Whenever I make a request, the request.body is returning as undefined

Below is the code snippet for my Express application using TypeScript version 3.7.4: import bodyParser from "body-parser"; import config from "config"; import cookieParser from "cookie-parser"; import express from "express"; import mongoose from "mongoose ...

Is there a way to sort through objects in a JSON file using two shared values? Specifically, I'm looking to filter the JSON objects based on both common x and y values

Given a JSON file, I am looking to group objects based on common x and y values. Essentially, I want to group together objects that share the same x and y properties. Here is an example of the JSON data: let data = [{ "x": "0", "y& ...

Attempting to remove the current click event listener and add a new event listener

I am attempting to remove the click event binding and replace it with another click event after the button has been clicked once. <small id="selectall_agriculture" onclick="refineSearch.testing('agriculture')">(select all)</small> O ...

Exploring the implementation of waterfall in a Node.js application

async.traverse(map, function(item, tnext){ async.waterfall([ function(wnext){ console.log("One"); //performing MongoDB queries db.collection.find().toArray(function(err){ if(err){ ...

Here is a way to prevent a null input value from being accepted in a JavaScript function

Hey there, I have a function that looks like this: class Fun { pem_Files_Checker_And_Adder_Server_Id_Adder(id , serverType , hostname) { //do something }; }; } In order for this function to work properly, I need to give it some values. For exam ...

"Unlocking the power of Webdriver.io: Sending information to a personalized reporting system

Utilizing the wdio tool provided by the webdriver.io npm package is how I execute Mocha test-cases. The snippet below showcases a segment of the wdio.conf.js file: var htmlReporter = require('./js/reporter/htmlReporter'); htmlReporter.reporterN ...

Is there a way to improve error readability in React when using webpack?

Attempting to solve the issue, I decided to make a change in my npm script. Initially, it was set to operate in production mode by default: The original script looked like this: "client": "webpack -w --config ./gen/config/webpack.config.js& ...

Integrating new information into an existing JSON file using React Native

Currently, I am attempting to input new data into an existing JSON file using text input. In my project using React Native, I have a JSON file named PartyInfo.json where certain data is stored. The goal is to have this data passed from a form and saved in ...

Accessing local JSON data through JavaScript

I am looking to access a JSON file locally using JavaScript. The file is named "posts.json" and contains the following information: { "post0": "<empty>", //1 "post1": "<empty>", //2 "post ...

Ways to alter a PHP variable with each AJAX request

Utilizing AJAX to dynamically add more content to an image gallery. I'm passing a PHP variable to dictate the current page number and other necessary data. Each time new data is fetched via AJAX, I want to increment the page variable by one to fetch ...

If the handler of an event listener in jQuery requires a callback function, be sure to detach the event

Currently, I am facing a dilemma with a listener I have: $(document).on("keypress", function(e){ebClose(e,mpClose)}); I am exploring ways to dynamically delete this listener. The issue lies in the fact that I specifically want ebClose to receive mpClose ...

Steps for creating a personalized query or route in feathersjs

I'm feeling a bit lost and confused while trying to navigate through the documentation. This is my first time using feathersjs and I am slowly getting the hang of it. Let's say I can create a /messages route using a service generator to GET all ...