skip to Main Content

I have a JavaScript object array which has these attributes:

[
  {
    active: true
    conditionText: "Really try not to die. We cannot afford to lose people"
    conditionType: "CONDITION"
    id: 12
    identifier: "A1"
    superseded: false
    themeNames: "Star Wars"
    type here
  },
  {
    active: true
    conditionText: "Really try not to die. We cannot afford to lose people"
    conditionType: "CONDITION"
    id: 12
    identifier: "A1"
    superseded: false
    themeNames: "Star Wars"
    type here
  }
]

I want to get only 3 attributes from there (active, condtionText, id) and create a new array.

I tried filter method and but couldn’t get the result.
Any help regarding this highly appreciated.

2

Answers


  1. Is this what you are looking for?

    you could use Array.prototype.map() – MDN Document

    simple code:

    let originalArray = [
        {
            id: 12,
            active: true,
            conditionText: "Really try not to die. We cannot afford to lose people",
            conditionType: "CONDITION",
            identifier: "A1",
            superseded: false,
            themeNames: "Star Wars"
        },
        {
            id: 12,
            active: true,
            conditionText: "Really try not to die. We cannot afford to lose people",
            conditionType: "CONDITION",
            identifier: "A1",
            superseded: false,
            themeNames: "Star Wars"
        }
    ]
    
    let newArray = originalArray.map(obj => ({
        id: obj.id,
        active: obj.active,
        conditionText: obj.conditionText
    }));
    
    console.log(newArray);
    

    Demo:
    enter image description here

    Login or Signup to reply.
  2. Here’s a way to do it:

    function extractProperties (keys, input) {
      if (Array.isArray(input)) {
        return input.map(obj => extractProperties(keys, obj));
      }
      
      return Object.fromEntries(keys.map(key => [key, input[key]]));
    }
    
    const array = [
      {
        active: true,
        conditionText: "Really try not to die. We cannot afford to lose people",
        conditionType: "CONDITION",
        id: 12,
        identifier: "A1",
        superseded: false,
        themeNames: "Star Wars"
      },
      {
        active: true,
        conditionText: "Really try not to die. We cannot afford to lose people",
        conditionType: "CONDITION",
        id: 12,
        identifier: "A1",
        superseded: false,
        themeNames: "Star Wars"
      }
    ];
    
    function extractProperties (keys, input) {
      if (Array.isArray(input)) {
        return input.map(obj => extractProperties(keys, obj));
      }
      
      return Object.fromEntries(keys.map(key => [key, input[key]]));
    }
    
    const result = extractProperties(['active', 'conditionText', 'id'], array);
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search