简体   繁体   English

根据键从 object 创建值数组

[英]Create an array of values from object based on key

If I have an object如果我有一个 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:一种方法是只执行过滤器,然后 map object 查找:

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

Or, use Object.entries to get both keys and values:或者,使用Object.entries获取键和值:

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:您可以使用Object.entries获取键值对列表,并.forEach对其进行迭代:

 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.您可以在Object.entries上使用reduce方法并检查键是否以特定字符串startsWith

 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 : Object.entries获取条目,然后过滤以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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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