catmal
catmal

Reputation: 1758

Create an array of values from object based on key

If I have an object

post = {
title: "Title",
image_1: "1234",
image_2: "2345"
}

and I want to get an array:

["1234", "2345"]

This is how I filter attributes to be included in the array

Object.keys(post).filter(key =>
  key.includes("image")
);

and get an array of correct keys. How do I get values instead?

Upvotes: 3

Views: 98

Answers (5)

Alan Omar
Alan Omar

Reputation: 4217

Object.entries to obtain entries, then filter those which starts with image:

let post={title:"Title",image_1:"1234",image_2:"2345"};

let result = Object.entries(post)
.filter(e => e[0].startsWith('image'))
.flatMap(e => e[1])

console.log(result)

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28414

You can use Object.entries to get a list of key-value pairs, and .forEach to iterate over it:

const post = {
  title: "Title",
  image_1: "1234",
  image_2: "2345"
};

const res = [];

Object.entries(post).forEach(([key,value]) => {
  if(key.includes("image")) res.push(value);
});

console.log(res);

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122047

You could use reduce method on Object.entries and check if the key startsWith a specific string.

const post = {
  title: "Title",
  image_1: "1234",
  image_2: "2345"
}

const result = Object
  .entries(post)
  .reduce((r, [k, v]) => {
    if (k.startsWith('image')) r.push(v);
    return r;
  }, [])

console.log(result)

Upvotes: 0

Aplet123
Aplet123

Reputation: 35512

One way is to just do your filter then map the object lookup:

Object.keys(post)
    .filter(key => key.includes("image"))
    .map(key => post[key])

Or, use Object.entries to get both keys and values:

Object.entries(post)
    .filter(([key, value]) => key.includes("image"))
    .map(([key, value]) => value)

Or, with a "filter and map" operation:

Object.entries(post)
    .flatMap(([key, value]) => key.includes("image") ? [value] : [])

Upvotes: 4

Michiel
Michiel

Reputation: 353

const post = { title: "Title", image_1: "1234", image_2: "2345" };
const keys = Object.keys(post).filter(key => key.includes("image"));
const output = keys.map(key => post[key]);
console.log(output); // [ '1234', '2345' ]

Upvotes: 0

Related Questions