Retrieve specific attributes from each object in an array

I have an array of objects containing numerous properties. I am looking to create a new array that only includes specific key-value pairs:

const sampleArray = [
    { "key1": "value1", "key2": "value2", /* … */, "key100": "value100" },
    { "key1": "value1", "key2": "value2",  /* … */, "key100": "value100" },
    // …
  ];

What's the best way to filter, map, reduce, or use another method to extract the desired keys from the array?

const newArr = sampleArray.map(function(obj) { 
    delete obj.key1; 
    delete obj.key3;
    delete obj.key15;
    // Long list …

    return obj; 
  });

Is there a way to retain only key20, key30, key70, key80 for each object and remove all others?

Answer №1

Utilize object destructuring for extracting the properties and constructing a new object with shorthand property names:

const data = [{ "att20": "att20", "att30": "att30", "att70": "att70", "att80": "att80"}, { "att20": "att20", "att30": "att30", "att70": "att70", "att80": "att80"}];

const modifiedData = data.map(({ att20, att30, att70, att80 }) => ({
  att20,
  att30,
  att70,
  att80
}));

console.log(modifiedData);

Answer №2

When using the map function to create a new array, there is no need to delete any elements. Instead, you can simply create an array of interesting keys and return it.

var dummyArray = [{
  "att1": "something",
  "att2": "something",
  "att20": "something",
  "att100": "something"
}, {
  "att1": "something",
  "att2": "something",
  "att20": "something",

  "att100": "something"
}];

let x = dummyArray.map((item) => {
  return {
    attr20: item.att20
  }

})

console.log(x)

Answer №3

Utilize an array to store the properties you wish to retain, and then iterate through each object to transfer the desired properties to a new object.

var data = [{ "name": "John", "age": 30, "city": "New York"}, { "name": "Emily", "age": 25, "city": "Los Angeles"}];

var propertiesToKeep = ["name", "city"];

var newData = data.map(item => {
  const newObj = {};
  for (const prop of propertiesToKeep) {
    newObj[prop] = item[prop];
  }
  return newObj;
})

console.log(newData)

Answer №4

I've discovered the simplest solution to this problem using JSON.stringify()

The JSON.stringify() function in JavaScript converts an object or value into a JSON string. It can also replace values with a specified replacer function, or include only certain properties with a replacer array.

    const data = [
      { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55 },
      { "id": "0002", "type": "ansd", "name": "EARK", "ppu": 0.67 }
    ];
    const jsonData = JSON.stringify(data, ['id', 'type']);
    console.log(jsonData);

Answer №5

Here is a useful function that extracts only the specified properties from an object, based on an array of desired properties passed as a parameter.

The advantage of using this function is that it provides a more direct and cleaner way to extract properties, especially when dealing with extracting properties from a single object.

If you have a list of objects, you can easily map through the list and perform property extraction in each iteration.

function objectExtract(obj, properties) {
    return properties.reduce((result, prop) => {
        if (obj.hasOwnProperty(prop)) {
            result[prop] = obj[prop];
        }
        return result;
    }, {});
}

You can learn more about reduce here.

Usage example:

(a real-world example involving Redux)

store.dispatch(
    setRooms({ 
        ...roomsState,
        list: rooms.reduce((list, room) => {
            list[room.id] = objectExtract(room, ['name', 'description', 'createdAt', 'updatedAt']);
            return list;
        }, {})
    })
)

(Based on the example provided in the question)

var dataSourceArray = [{
    "att1": "something",
    "att2": "something",
    "att20": "something",
    "att100": "something"
}, {
    "att1": "something",
    "att2": "something",
    "att20": "something",

    "att100": "something"
}];

let x = dataSourceArray.map((item) => {
    return objectExtrac(item, ['att100', 'att2']);
});

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 exactly does "nothing" mean in Node when using async await?

I have a method as shown below: private async sendToAll(clients) { for(const client of clients) { this.send(client, message); await true; // What should I put here to allow the rest of the application to continue executi ...

Transitionend event fails to trigger when Chrome tab is not in focus

$("#element").addClass("myclass").on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function (e) { $("#element").addClass('text-success'); $("#element2").addClass('myclass2'); setTimeout(function () { ...

Issue with Angular's ng-show failing to display an image post-processing

$scope.showProcessedGraph = function(hash) { if ($scope.selectedFile.hash == hash) return; $scope.graph = ""; $scope.isImageLoaded = false; $scope.isLoading = true; if (hash) { $http({ m ...

What is the best way to initiate an image loop with the click of a button?

<p align="center"> <button onclick="slideit()">Run the loop</button> <!-- Start Weather Image Loop --> <img src="firstcar2.gif" name="slide" width="900" height="500" /> <script type="text/javascript"> <!-- var ...

How can I use HTML and Javascript to toggle the visibility of a 'select' element, like a dropdown menu

After adding a dropdown and label within a div, I expected them to hide and unhide when the div is manipulated with a function. However, it seems that this functionality is not working as expected. function ToggleDiv(DivID) { if (document.getElementBy ...

You can't scroll vertically to the top of the form within a specific height range

Hey there! I've put together a simple form using bootstrap, but I've run into an issue. When I resize the screen (in height), I can't scroll all the way to the top of the form. If you want to take a look, here's the link: http://jsbin. ...

How can I use the draggable and droppable features to add <li> elements to a <ul> list?

I'm encountering a small issue with controlling the placement of my <li> elements when I implement draggable and droppable from JQuery UI. To better explain the problem, I have created a detailed fiddle: JSFiddle Why is it that the .courseBox ...

Issue with Jquery toggle functionality only affecting a single div

Is there a way to make a div display one of two images depending on which div the user hovers over? The code provided below works for hovering over #FH_Blurb, but does not work for hovering over #HDS_Blurb. Could you explain why this is happening? Both im ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

Repurpose the identical popup window

I am searching for a solution to use the same pop-up window whenever it is called. Currently, I need to submit a form into a pop-up window and it works well, except in Chrome iOS where each form submission opens a new tab/window instead of reusing the prev ...

"Endless loop error in Three.js causing a system crash

I'm currently in the process of developing a library that consists of 'letter' functions responsible for generating letters in vertex coordinates. The main objective here is to allow users to create words or sentences using an interactive Po ...

What is the best way to transform a data dictionary into an array in Swift programming language?

When retrieving data from Firebase, I receive it back as a dictionary of dictionaries: guard let data = snapshot.value as? [String: [String:Int]] else { I need to extract the first key if the data looks like this: "café-veritas": ["AmpleSeating": 1, ...

Displaying PHP output within a JavaScript expression

Let's dive into a scenario involving a basic HTML document and some JavaScript that's loaded within it: <!-- doc.html --> <!doctype html> <html lang="en"> <head> <script type="text/javascript" src=" ...

The Yeoman/Grunt-usemin is failing to update the index.html file even after adding new JavaScript code

As I work on developing a web app using Yeoman and the Angular generator on Windows 7, I go through the process of running 'yo angular' followed by 'grunt' to build the app for deployment. The index.html file in the dist folder gets upd ...

AngularJS - Smoothly navigate to the top of the page by swiping left or right

I'm currently working on a project in angularJS and ionic that involves a slidebox with three slides, each containing different content. My goal is to scroll back to the top every time I switch between slides. Initially, I thought using on-swipe-left ...

React throwing error: Context value is undefined

Why is the Context value showing as undefined? The issue lies in src/Context.js: import React, { Component } from 'react'; const Context = React.createContext(); export class Provider extends Component { state = { a: 1, b: 2 }; render( ...

Issues with AngularJS directives properly binding attributes

As a newcomer to the world of Angular, I have embarked on my first complex directive project and find myself slightly perplexed. My goal is to construct a reusable list of items organized into separate tabs within my application. The list operates uniforml ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...

Attempting to postpone the execution by using setTimeout() within a loop

Currently, I am in the process of creating an automated script for a gambling website. Specifically, I am focusing on the roulette game mode where you have 20 seconds to choose a color and 10 seconds for the outcome to be revealed each round. My goal is to ...

Is it time to ditch Internet Explorer for EDGE?

Have you ever noticed that when attempting to access the stackoverflow website on Internet Explorer, the tab mysteriously closes and Microsoft Edge opens with stackoverflow loaded? What is the secret behind this strange phenomenon on stackoverflow's ...