Home > OS >  Best approach in extracting the values of array inside object in js
Best approach in extracting the values of array inside object in js

Time:06-10

What is best approach in extracting the below object. I tried two ways. Can this be refactored in any other way to optimize the performance?

const data = {
    "postcode": [
        "123456"
    ],
    "time": [
        "05:11"
    ]
};

Approach 1:

for (const element of Object.entries(data)) {
    const key = element[0];
    const value = element[1][0];
    data[key] = value;
}

Approach 2:

for (const key in data) {
    if (Object.hasOwnProperty.call(data, key)) {
        data[key] = data[key][0];
    }
}

console.log('data ', data);

CodePudding user response:

A concise method is this:

for (const [key, [value]] of Object.entries(data)) {
    data[key] = value
}

Notice the extra set of [] around [value] to extract the value from that array immediately too.

Of course, conciseness isn't always better and you may prefer your other solutions if you think they are more readable.

In terms of performance this isn't any better than your first solution. Your second option will be more memory efficient though it heavily depends on the size and shape of your object.

CodePudding user response:

This approach will solve your problem. MDN recommended!

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"

CodePudding user response:

const data = {
    "postcode": [
        "123456"
    ],
    "time": [
        "05:11"
    ]
};


for (const element of Object.entries(data)) {
    data[element[0]] = element[1][0];
}



console.log('data ', data);

  • Related