Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes:

[
  {
    active: true
    conditionText: "Really try not to die. We cannot afford to lose people"
    conditionType: "CONDITION"
    id: 12
    identifier: "A1"
    superseded: false
    themeNames: "Star Wars"
    type here
  },
  {
    active: true
    conditionText: "Really try not to die. We cannot afford to lose people"
    conditionType: "CONDITION"
    id: 12
    identifier: "A1"
    superseded: false
    themeNames: "Star Wars"
    type here
  }
]

I am looking to extract only three attributes from this array (active, condtionText, id) and create a new array.

I attempted using the filter method but did not achieve the desired result. Any assistance on this matter would be greatly appreciated.

Answer №1

Are you searching for this solution?

You may consider utilizing Array.prototype.map() - MDN Document

Here is a brief code snippet:

let originalArray = [
    {
        id: 12,
        active: true,
        conditionText: "Really try not to die. We cannot afford to lose people",
        conditionType: "CONDITION",
        identifier: "A1",
        superseded: false,
        themeNames: "Star Wars"
    },
    {
        id: 12,
        active: true,
        conditionText: "Really try not to die. We cannot afford to lose people",
        conditionType: "CONDITION",
        identifier: "A1",
        superseded: false,
        themeNames: "Star Wars"
    }
]

let newArray = originalArray.map(obj => ({
    id: obj.id,
    active: obj.active,
    conditionText: obj.conditionText
}));

console.log(newArray);

Check out the demonstration: https://i.sstatic.net/X69A6.jpg

Answer №2

Check out this method:

function retrieveKeys (identifiers, data) {
  if (Array.isArray(data)) {
    return data.map(item => retrieveKeys(identifiers, item));
  }
  
  return Object.fromEntries(identifiers.map(identifier => [identifier, data[identifier]]));
}

const itemList = [
  {
    active: true,
    description: "Do not give up",
    category: "General",
    id: 45
  },
  {
    active: false,
    description: "Keep moving forward",
    category: "Motivational",
    id: 67
  }
];

function retrieveKeys (identifiers, data) {
  if (Array.isArray(data)) {
    return data.map(item => retrieveKeys(identifiers, item));
  }
  
  return Object.fromEntries(identifiers.map(identifier => [identifier, data[identifier]]));
}

const output = retrieveKeys(['active', 'description'], itemList);

console.log(output);

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

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

Create an array by copying elements from another array object

My goal is to merge the data from two arrays, array1 and array2, into a new array called array3. Here's how I want it structured: array 1 objects: userName, userId array 2 objects: userId, msg I aim to obtain an array3 consisting of: userId, userNa ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

Triggering the Bootstrap modal multiple times with each increment

I am experiencing an issue with Bootstrap Modal where the action fires up multiple times upon clicking. <div id="loginModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> ... & ...

Here's a unique version: "Steps for replacing an outdated chart with a new one using Chart.js and

Is there a way to remove an old chart when the user clicks a button to retrieve a new chart? I understand that the existing chart needs to be destroyed before a new one is generated, but currently, the code does not support destroying non-globally create ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

Display the variable on the document by clicking the button

Hello, I'm new here so please forgive me if I make any mistakes. I am working with the following PHP code: <?php $quoteFile = "quotes.txt"; //Store quotes in this file $fp = fopen($quoteFile, "r"); //Open file for reading $content = fread ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

Show data based on the chosen destination

Recently, I've been working on creating a simple printer manager to monitor the status of all my printers. Although I have successfully displayed all the data, I'm facing an issue while trying to organize it by location. The error message I keep ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

Looking for assistance with retrieving all files from a directory based on their file extensions in JavaScript

Looking for a way to gather all the '.txt' files from a folder that also contains a 'backup' folder, and moving them into the 'backup' folder using Node.js. If you have any suggestions, please share. Thanks! Best regards, M ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...

Is there a way to determine if an npm package is compatible with a specific version of Angular

As I work on my project, I realize that I have many dependencies on libraries that support Angular2 but not Angular6. It can be challenging to determine if a library supports Angular2 from just reading their GitHub pages. One idea is to check the package ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Implementing user profile picture display in express.js: A step-by-step guide

I'm having trouble displaying the profile picture uploaded by users or employees in my application. Although the picture uploads successfully, it doesn't show up and gives an error when I try to redirect to the page. Cannot read property &ap ...

When initialized within an object, Angular may identify a field as undefined

Whenever I attempt to access a property of the object named "User," it shows up as undefined. However, upon logging the complete object to the console, the field appears with the necessary data. Here is the console log output: perfil.component.ts:42 unde ...

The client side script "/socket.io/socket.io.js" was not located, therefore the Express-generator project was used instead

I have been working on integrating the "chat-example" from Socket.IO's official website into an Express-generator generated project while keeping the structure of the project intact. I have made minimal changes to the code to fit it into the existing ...

Creating an enum from an associative array for restructuring conditions

Hey everyone, I have a situation where my current condition is working fine, but now I need to convert it into an enum. Unfortunately, the enum doesn't seem to work with my existing condition as mentioned by the team lead. Currently, my condition loo ...