Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading