How to remove unwanted elements in JavaScript object array and create a new array

49 Views Asked by At

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

There are 2 best solutions below

1
pickuse On

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

4
Hao Wu On

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