3

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?

3
  • Use Object.values instead of Object.keys. Do you want a value based on the key or get all of the values from includes or something? Commented Dec 30, 2020 at 20:31
  • But I need to filter attributes based on key Commented Dec 30, 2020 at 20:32
  • Ight, Use Object.entries and compare using the object's key Commented Dec 30, 2020 at 20:34

5 Answers 5

4

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] : [])
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0
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' ]

Comments

0

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.