[英]Access value from JSON object based on if ID is in a nested object
我有一个 json object 嵌套在父 json 对象的参数中。 我正在尝试根据子对象的 ID 字段中是否存在 ID 来访问父级的属性。
JSON结构如下:
{
id: 1,
map: "test",
parameter_definitions: [{ID: 1, parameterUnits: "%"},{ID: 2, parameterUnits: "%"}],
},
{
id: 2,
map: "test2",
parameter_definitions: [{ID: 3, parameterUnits: "%"},{ID: 4, parameterUnits: "%"}],
}
我需要返回的值是右侧 json object 的 map,这取决于我的给定值是否是 parameter_definitions ZA8CFDE89666993AC 中的 ID 之一我似乎无法理解这是由什么组成的。
也许这个 function "getMapElementById" 会帮助你:
let maps = [{ id: 1, map: "test", parameter_definitions: [{ID: 1, parameterUnits: "%"},{ID: 2, parameterUnits: "%"}], }, { id: 2, map: "test2", parameter_definitions: [{ID: 3, parameterUnits: "%"},{ID: 4, parameterUnits: "%"}], }] function getMapElementById( maps, requiredId ) { for(let i=0;i<maps.length;i++){ for(let j=0;j<maps[i].parameter_definitions.length;j++){ if( maps[i].parameter_definitions[j].ID == requiredId ) { return maps[i]; } } } } let mapResult = getMapElementById(maps, 3); console.log(mapResult);
不幸的是,你的问题不是很清楚。 这是你想要的?
// const objectScan = require('object-scan'); const myData = [{ id: 1, map: 'test', parameter_definitions: [{ ID: 1, parameterUnits: '%' }, { ID: 2, parameterUnits: '%' }] }, { id: 2, map: 'test2', parameter_definitions: [{ ID: 3, parameterUnits: '%' }, { ID: 4, parameterUnits: '%' }] }]; const getRootElement = (data, id) => objectScan(['[*].parameter_definitions[*].ID'], { abort: true, filterFn: ({ value, parents, context }) => { if (value === id) { context.push(...parents); return true; } return false; } })(data, [])[2]; console.log(getRootElement(myData, 5)); // => undefined console.log(getRootElement(myData, 3)); // => { id: 2, map: 'test2', parameter_definitions: [ { ID: 3, parameterUnits: '%' }, { ID: 4, parameterUnits: '%' } ] }
.as-console-wrapper {max-height: 100%;important: top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
免责声明:我是对象扫描的作者
目前尚不清楚多个父对象是否可以拥有具有相同 id 的子 object,但无论哪种方式,您都可以使用过滤器的组合并找到:
let objects = [
{
id: 1,
map: "test",
parameter_definitions: [{ ID: 1, parameterUnits: "%" }, { ID: 2, parameterUnits: "%" }],
},
{
id: 2,
map: "test2",
parameter_definitions: [{ ID: 3, parameterUnits: "%" }, { ID: 4, parameterUnits: "%" }],
}
];
let filteredObjects = objects.filter(object => object.parameter_definitions.find(param => param.ID === 2));
if (filteredObjects.length > 0) {
// If you know there will only be one parent object per child object ID, just return the first from the array
console.log(filteredObjects[0].map);
// If several parent objects can have the same child object ID, you can use the map function to get the map property of all the parent objects
console.log(filteredObjects.map(object => object.map));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.