简体   繁体   中英

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?

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] : [])

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

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM