Home > Enterprise >  How do I convert an array of objects to an array including only one property's values?
How do I convert an array of objects to an array including only one property's values?

Time:01-14

I am trying to use the .includes( ) array method to check if an item is in my JSON file. So far I have made a connection to the database (using JSON server npm plugin) and have retrieved the array of objects back, and stored them in the variable "fetchedData". Now, I know that .includes( ) takes an array as the first argument and searches within the array for the second argument. How do I convert this array of objects to an array including just the name property values? Is this how .includes( ) works?

This is the JSON file:

  "savedexercises": [
    {
      "name": "all fours squad stretch",
      "target": "quads",
      "gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1512.gif",
      "id": 1
    },
    {
      "name": "ankle circles",
      "target": "calves",
      "gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1368.gif",
      "id": 2
    },
    {
      "name": "arm slingers hanging bent knee legs",
      "target": "abs",
      "gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/2355.gif",
      "id": 3
    }
  ]
}

I am just trying to access all the name property values and then store them into an array.

CodePudding user response:

You can you filter and map to find all the values of a particular key and transform it to an array of objects or any form. Includes will only tell you if such a key exists. Refer the code below

  const createArraybasedOnkey= (key) => {
    console.log(
      obj.savedexercises
        .filter((x) => x[key])
        ?.map((x) => {
          return { [key]: x[key] };
        })
    );
  };

code sandbox : https://codesandbox.io/s/pedantic-rain-u1t9th?file=/src/App.js:625-817

CodePudding user response:

Use array.map(). For example:

const exerciseNames = savedexercises.map(exercise => exercise.name)
// Expected output:
// ["all fours squad stretch", "ankle circles",
//  "arm slingers hanging bent knee legs"]

// Now you can check if the exerciseNames includes a certain exercise:
console.log(exerciseNames.includes("all fours squad stretch"))
// Expected output: true
  • Related