Home > Blockchain >  How to find multiple property values from an array of objects?
How to find multiple property values from an array of objects?

Time:11-04

I have an array of objects like,

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

and I want to find say age and address from this object, what is the recommended and optimal way to do that? For real application, I might have 20-40 key-value objects in this array, out of which I might want to access 5-10 values.

What I do right now is I loop through this object and use conditions to find and assign values to my variables. but in this approach, I have to write multiple else if expressions (5-10).

For example,

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;
    }};

CodePudding user response:

You will always have to write explicitly "name", "points",... because you can't parse string value and use it to identify variable with the same name. But to avoid using multiple else if, maybe the switch case statement is more appropriate and readable?

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;
    }
};

CodePudding user response:

You can simply achieve this requirement with the help of Array.filter() along with Array.map() method.

Live Demo :

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

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

const res = customer1.filter(obj => searchKeys.includes(obj.key)).map(({ value}) => value);

const [age, address] = res;

console.log(age);
console.log(address);

  • Related