How to retrieve specific key values from an array in JavaScript?

I am trying to extract certain key values, specifically ‘serviceCode’, from an array of objects in JavaScript. Can someone guide me on how to achieve this? Below is a sample code snippet:

var data = {
    "0": JSON.stringify({"carrier":"ups","service":"ground","cost":"28.66"}),
    "1": JSON.stringify({"carrier":"ups","service":"second_day","cost":"69.72"}),
    "2": JSON.stringify({"carrier":"ups","service":"next_day","cost":"76.62"})
};

var result = [];
Object.keys(data).forEach(function(key) {
    result.push(JSON.parse(data[key]));
});

console.log(result.service); // This returns undefined

To extract specific key values from an array of objects in JavaScript, you need to iterate over each object in the array and access the desired keys. In your case, you are dealing with an object that contains serialized JSON strings, which need to be parsed first. Here's an improved version of your code to extract the service property from each object:

var data = {
    "0": JSON.stringify({"carrier":"ups","service":"ground","cost":"28.66"}),
    "1": JSON.stringify({"carrier":"ups","service":"second_day","cost":"69.72"}),
    "2": JSON.stringify({"carrier":"ups","service":"next_day","cost":"76.62"})
};

var services = [];

Object.keys(data).forEach(function(key) {
    var parsedData = JSON.parse(data[key]);
    services.push(parsedData.service);
});

console.log(services); // Logs: ['ground', 'second_day', 'next_day']

Here's a breakdown of what happens in the code:

  • JSON.parse(): Converts the JSON string back into an object so you can access its properties.
  • Iterate: Use Object.keys() to get an array of keys and then iterate over each key with forEach.
  • Access and Collect: During each iteration, extract the service property from the parsed object and store it in the services array.

This approach efficiently gathers the service values into an array for easy use in further processing or output.

To extract the service values from your array of objects, you'll need to parse the JSON strings and collect each service key's value. Here's a concise way to achieve this:

var data = {
    "0": JSON.stringify({"carrier":"ups","service":"ground","cost":"28.66"}),
    "1": JSON.stringify({"carrier":"ups","service":"second_day","cost":"69.72"}),
    "2": JSON.stringify({"carrier":"ups","service":"next_day","cost":"76.62"})
};

var services = Object.keys(data).map(key => JSON.parse(data[key]).service);

console.log(services); // Logs: ['ground', 'second_day', 'next_day']

Here's how it works:

  • Use Object.keys() to get an array of keys from data.
  • map() over these keys, parsing each JSON string and extracting the service attribute.

This results in an array of service values.