Ways to retrieve multiple property values from an array of objects

My data consists of an array of objects which look like this:

customer1 = [
    {"key": "name",
     "value": "Peter"},
    {"key": "age",
     "value": 23},
    {"key": "address",
     "value": "xyz St, abcd"},
    {"key": "points",
     "value": 234}
    ]

In order to retrieve specific information such as age and address from these objects efficiently, I'm looking for the best approach. In a real scenario, my array may contain anywhere from 20 to 40 key-value pairs, but I might only need to access 5 to 10 values.

Currently, I iterate through the object using conditions to extract and assign values to variables. However, this method involves writing multiple else-if statements (5-10).

Here is an example of what I currently do:

let name: string;
let points: number;

for (var item of customer1) {
    if (item.key === "name") {
        name = item.value;
    } else if (item.key === "points") {
        points = item.value;
    }};

Answer №1

To fulfill this requirement, you can utilize the powerful combination of Array.filter() and Array.map() methods.

Check out a demonstration of this in action below:

const customerDetails = [
  { "key": "name", "value": "Peter" },
  { "key": "age", "value": 23 },
  { "key": "address", "value": "xyz St, abcd" },
  { "key": "points", "value": 234 }
];

const keysToSearch = ['age', 'address'];

const results = customerDetails.filter(obj => keysToSearch.includes(obj.key)).map(({ value }) => value);

const [customerAge, customerAddress] = results;

console.log(customerAge);
console.log(customerAddress);

Answer №2

When working with a data structure like CustomerProperty, it is necessary to explicitly reference the keys such as "name" and "points". This approach prevents parsing issues when trying to dynamically identify variables based on string values. To streamline this process and enhance readability, consider using a switch case statement instead of multiple else if conditions.

interface CustomerProperty {
    key: string,
    value: string | number
}

let customer1: CustomerProperty[] = [
    {
        "key": "name",
        "value": "Peter"
    },
    {
        "key": "age",
        "value": 23},
    {
        "key": "address",
        "value": "xyz St, abcd"},
    {
        "key": "points",
        "value": 234
    }
];

let nameValue: string;
let pointsValue: number;
for (var item of customer1) {
    switch (item.key) {
        case "name":
            nameValue = item.value as string;
            break;
        case "points":
            pointsValue = item.value as number;
            break;
    }
};

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

Sending a style prop to a React component

My typescript Next.js app seems to be misbehaving, or perhaps I'm just not understanding something properly. I have a component called <CluckHUD props="styles.Moon" /> that is meant to pass the theme as a CSS classname in order to c ...

Jerky visuals on the canvas

My canvas animation runs smoothly in Chrome, but it's as choppy as a bad haircut in Firefox. Surprisingly, the code is not even that complex. Is there anything in my code that could be causing this slowdown? Here is the jsfiddle link for reference: h ...

Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated. app.component.ts: ngOnInit(): void ...

Go all the way down to see the latest messages

I have developed a messaging system using Vue. The latest messages are displayed from bottom to top. I want to automatically scroll to the end of a conversation when it is clicked and all the messages have been loaded via axios. Conversation Messages Comp ...

Retrieving the data from a Material UI Slider control

I'm encountering an issue with retrieving the value property I assigned to a component. event.target.value is returning undefined. How can I successfully access the value of the component? My goal is for handlePlayersChange() to be able to handle dyn ...

Issue with Vue.js: routes are not found upon page refresh

Here is a basic vue-routing example: const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/ba ...

Direct back to the current page post deleting entry from mongodb

After removing data from MongoDB, how can I redirect to the same view (handlebar)? I tried using res.render, but it shows that the website cannot be reached. Thank you for your assistance. Controller Logic var express = require('express'); va ...

What is causing the permissions in firestore to not function properly?

My custom code changed(){ let reference = db.collection('messages').orderBy('timestamp') // listen for changes to the 'messages' collection reference.onSnapshot(snapshot => { snapshot.docChanges().forEach(change => ...

Opening a fresh window and dynamically populating form fields with Javascript

Recently, I've been diving into the world of JavaScript and attempting to create a functionality where a new window is launched on click after a user inputs information into form fields. The challenge lies in transferring this information into form fi ...

Is there a way to retrieve all the items from the array?

I've been on the hunt for this information but unfortunately, I haven't found a satisfactory answer yet. Currently, I am utilizing Json encode to transfer my array to JavaScript: In PHP while($row = mysql_fetch_assoc($select)) { $event_day = $ ...

What is the best way to send file data using the form-data format in Postman with React?

When I first started working with React, I encountered the need to transmit data from the frontend to the backend using an API. The data was in the form of form-data from POSTMAN, as shown in the image below. https://i.sstatic.net/U9QMe.png I opted to us ...

What is the best way to remove the left margin from a MuiTreeItem-group?

I'm working with the MUI tree component and I want to remove the left margin of the second layer of MuiTreeItem-group I attempted to use makeStyles to address this issue, but it didn't have the desired effect const useStyles = makeStyles(() => ...

Deleting query strings from the URL - HashRouter

In my application, I have a LoginContainer component that houses both a login-form and a signup-form. These components are displayed on the same page, with only one of them being rendered based on user interaction. While the functionality of the forms is ...

Unable to reach elements that have been loaded through ajax with jQuery

I am facing an issue where I cannot access content loaded via ajax for modification. Unfortunately, I do not have access to the js file responsible for the initial load. Therefore, I need to create a separate function to alter the content. The required mo ...

Expressjs encountering issues with response detection

I'm facing an issue with my nodeapp and Express setup. I have configured a reverse proxy through nginx to point to . However, when I start my application, it doesn't seem to recognize the / response. Below is my code snippet: var express = requ ...

What is the most efficient way to automatically start the Webpack-dev-server every time a file is

Is there a way to automatically run and refresh webpack-dev-server when I am using the Atom package called AutoSave OnChange while running my application? This is my configuration for webpack-dev-server: devServer: { contentBase: './src/inde ...

360 Panoviewer in Three.js exhibits low image quality and pixelated textures

I'm encountering an issue with the texture quality in my 360 panoviewer using Three.js. I've been working off of this code and it appears that my settings are consistent with the original. However, despite using the same image, my version seems ...

How can I display a div within a parent container in Angular 2?

Instead of pasting my loading modal pop-up to every page in the app, I want it to appear at the parent component (i.e. "app.component.ts"). This way, I can easily call it multiple times throughout the application. Now, I have pages with different routes t ...

What is the best way to show the associated ul tag?

I've constructed the following HTML: <input id="<code generated id>" type="text" value="select"/> <div id="<code generated id>" class="popup"> <ul id="<code generated id>" class="none"> <li>A</li& ...

Getting the (x,y) Coordinate Value from jQuery Script and Saving it as a NSString

div tag is essential for applying bold, italic, and various other formatting options in UIWebview. My goal is to retrieve the position coordinates when a user interacts with the div tag using JavaScript/jQuery. I stumbled upon the required code on JSFiddl ...