Home > Mobile >  Array of Objects -> filter keys or values by startsWith -> merge result to object
Array of Objects -> filter keys or values by startsWith -> merge result to object

Time:03-11

I have an array of objects:

let cars = [
  {
    "color_1": "purple",
    "color_2": "red",
    "type": "minivan",
    "capacity": 7,
    "all_colors": []
  },
  {
    "color_1": "blue",
    "color_2": "orange",
    "type": "station wagon",
    "capacity": 5,
    "all_colors": []
  }
]

I want to filter all keys (startsWith) "color..." and merge them into "all_colors" like this:

let cars = [
  {
    "color_1": "purple",
    "color_2": "red",
    "type": "minivan",
    "capacity": 7,
    "all_colors": ['purple', 'red']
  },
  {...}
]

I tried this:

var res = Object.keys(Object.assign({}, ...cars)).filter(v => v.startsWith('color'));
console.log(res)

but i need it for all objects and i don't know how to add the results into "all_colors"?

CodePudding user response:

You can do it like this:

let cars = [
  { "color_1": "purple", "color_2": "red", "type": "minivan" ,"capacity": 7, "all_colors": [] },
  { "color_1": "blue", "color_2": "orange", "type": "station wagon","capacity": 5, "all_colors": [] }
];

for (const car of cars) {
  const color_properties = Object.keys(car).filter((key) => key.startsWith('color'));
  car.all_colors = color_properties.map((color) => car[color]);
}

console.log(cars);

CodePudding user response:

You could get entries, filter and map the values.

const
    cars = [{ color_1: "purple", color_2: "red", type: "minivan", capacity: 7, all_colors: [] }, { color_1: "blue", color_2: "orange", type: "station wagon", capacity: 5, all_colors: [] }],
    result = cars.map(o => ({ ...o, all_colors: Object
         .entries(o)
         .filter(([k]) => k.startsWith('color'))
         .map(([, v]) => v)
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related