[英]How do I convert an array of objects to an array including only one property's values?
I am trying to use the.includes( ) array method to check if an item is in my JSON file.我正在尝试使用 .includes( ) 数组方法来检查某个项目是否在我的 JSON 文件中。 So far I have made a connection to the database (using JSON server npm plugin) and have retrieved the array of objects back, and stored them in the variable "fetchedData".
到目前为止,我已经连接到数据库(使用 JSON 服务器 npm 插件)并检索了对象数组,并将它们存储在变量“fetchedData”中。 Now, I know that.includes( ) takes an array as the first argument and searches within the array for the second argument.
现在,我知道 .includes() 将数组作为第一个参数并在数组中搜索第二个参数。 How do I convert this array of objects to an array including just the name property values?
如何将此对象数组转换为仅包含名称属性值的数组? Is this how.includes( ) works?
这是 how.includes( ) 的工作原理吗?
This is the JSON file:这是 JSON 文件:
"savedexercises": [
{
"name": "all fours squad stretch",
"target": "quads",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1512.gif",
"id": 1
},
{
"name": "ankle circles",
"target": "calves",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/1368.gif",
"id": 2
},
{
"name": "arm slingers hanging bent knee legs",
"target": "abs",
"gifUrl": "http://d205bpvrqc9yn1.cloudfront.net/2355.gif",
"id": 3
}
]
}
I am just trying to access all the name property values and then store them into an array.我只是想访问所有名称属性值,然后将它们存储到一个数组中。
You can you filter and map to find all the values of a particular key and transform it to an array of objects or any form.您可以过滤和 map 以查找特定键的所有值并将其转换为对象数组或任何形式。 Includes will only tell you if such a key exists.
includes 只会告诉您是否存在这样的密钥。 Refer the code below
参考下面的代码
const createArraybasedOnkey= (key) => {
console.log(
obj.savedexercises
.filter((x) => x[key])
?.map((x) => {
return { [key]: x[key] };
})
);
};
code sandbox: https://codesandbox.io/s/pedantic-rain-u1t9th?file=/src/App.js:625-817代码沙箱: https://codesandbox.io/s/pedantic-rain-u1t9th?file=/src/App.js:625-817
Use array.map()
.使用
array.map()
。 For example:例如:
const exerciseNames = savedexercises.map(exercise => exercise.name)
// Expected output:
// ["all fours squad stretch", "ankle circles",
// "arm slingers hanging bent knee legs"]
// Now you can check if the exerciseNames includes a certain exercise:
console.log(exerciseNames.includes("all fours squad stretch"))
// Expected output: true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.