javascript - 基于Javascript中数组列表中的值返回父键
问题描述
{
"arr1":[
{
"name":"something1",
"id":"233111f4-9126-490d-a78b-1724009fa484"
},
{
"name":"something2",
"id":"50584c03-ac71-4225-9c6a-d12bcc542951"
},
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"
},
{
"name":"something4",
"id":"ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7"
},
{
"name":"something5",
"id":"ef825dc3-003c-4740-955a-bb437cfb4199"
}
],
"arr2":
[
{
"name":"Unique",
"id":"43cf14ee58ea4d8da43e9a2f208d215c"}
]
}
这是以键和值作为数组的数组列表,我想根据特定值返回所有键;
例如:我想返回父键[arr1,arr2],原因是两个数组都包含一个值Unique,所以我想返回两个值的父键,分别是 arr1 和 arr2 。
注意:该列表可以有 n 个数组。
任何帮助,将不胜感激。提前致谢。
解决方案
最简单的方法是:
- 循环遍历对象中的键
- 检查数组是否包含名称为“唯一”的任何对象
- 如果是这样,请将 objects 键添加到数组中
const obj = {
"arr1": [{ "name": "something1", "id": "233111f4-9126-490d-a78b-1724009fa484" }, { "name": "something2", "id": "50584c03-ac71-4225-9c6a-d12bcc542951" }, { "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }, { "name": "something4", "id": "ce0374ba-6d9b-4ff5-98b1-1191d1d2a9a7" }, { "name": "something5", "id": "ef825dc3-003c-4740-955a-bb437cfb4199" }],
"arr2": [{ "name": "Unique", "id": "43cf14ee58ea4d8da43e9a2f208d215c" }],
"arr3": [{ "name": "No unique here","id": "Example" }]
}
// Create our array that will contain the keys
const keys = []
// Loop through each key in the object
for (const prop in obj) {
// Use .some to see if any of the objects in this array have the selected name
const containsUnique = obj[prop].some(o => o.name === 'Unique')
if (containsUnique) {
// Add the current key to the array
keys.push(prop)
}
}
// Use the array of keys which contain an object named "Unique"
console.log(keys)
推荐阅读
- azure-active-directory - 在组中添加 B2B 来宾用户以进行应用程序访问
- unity3d - 我正在尝试旋转我的角色以面对鼠标位置,仅相对于 Transform: (0,0,0)
- eclipse - 如何让 Verilog 在 Eclipse 中运行?
- python - Python REST API 给出内部服务器错误
- firebase - 过滤最新的重复 Firebase 文档
- php - Laravel 将数据存储到数据透视表 eloquent
- json - Powershell - 解析不一致的 Json 数据
- php - 如何直接在 HTML Table 上编辑 JSON 数据?
- c++ - 如何检测 NULL 字符串或不是 NULL 字符串
- python - BeautifulSoup 对象未使用“html.parser”从网页中提取 html 标记