我需要 JS 数组任务的帮助。
我有一个看起来像这样的数组:
const array = [
{name: 'Show_Everything__c', controllerName: null, value: true},
{name: 'Vehicle_Type__c', controllerName: 'Show_Everything__c', value: "Car"},
{name: 'Car__c', controllerName: 'Vehicle_Type__c', value: "BMW"},
{name: 'Model__c', controllerName: 'Car__c', value: '330i'}
];
我有一个代表这些对象名称之一的键。
我想要实现的是:
如果我的 key=Vehicle_Type__c
,我想检查 Vehicle_Type__c 是否作为 controllerValue 存在于对象数组中的某处,如果它存在,而不是将其添加到新数组,并且(基于此示例)因为 Vehicle_Type__c 存在于名称为 Car__c 的对象上,现在我想检查 Car__c 作为 controllerName 存在于某处。
所以我想要一个包含 const newArray = [Car__c, Model__c ]
我现在有类似的东西:
const dependentField = array.find(field => field.controllerName === key).name;
const dependentField_2 = array.find(field => field.controllerName === dependentField).name;
const dependentField_3 = array.find(field => field.controllerName === dependentField_2).name;
但我想要一些通用的东西,没有逻辑重复。
非常感谢任何想法或示例,非常感谢。
最佳答案
您可以创建一个函数来进行搜索并递归调用它。
方案一
简单的代码,理解逻辑(这个方案会修改一个初始的全局变量)
// Your data
const array = [
{name: 'Show_Everything__c', controllerName: null, value: true},
{name: 'Vehicle_Type__c', controllerName: 'Show_Everything__c', value: "Car"},
{name: 'Car__c', controllerName: 'Vehicle_Type__c', value: "BMW"},
{name: 'Model__c', controllerName: 'Car__c', value: '330i'}
];
// The final array with all founded names
const newArray = [];
// Your recursive function
const findName = (value) => {
array.forEach((item) => {
if (item.controllerName === value) {
// If the key exists, save in the array and make a new search with this key
newArray.push(item.name);
findName(item.name);
}
})
}
// Starts the application by calling the fuction with the initial desired value
findName("Vehicle_Type__c");
// Check the results
console.log(newArray);
解决方案2
使用不变性原则的更复杂方法
// Your data
const array = [
{name: 'Show_Everything__c', controllerName: null, value: true},
{name: 'Vehicle_Type__c', controllerName: 'Show_Everything__c', value: "Car"},
{name: 'Car__c', controllerName: 'Vehicle_Type__c', value: "BMW"},
{name: 'Model__c', controllerName: 'Car__c', value: '330i'}
];
// Your filter function
const findName = (value) => {
const filteredData = array.filter(item => item.controllerName === value);
const filteredName = filteredData.map(item => item.name);
return filteredName;
}
// Your recursive and immutable function
const findDependencies = (acc, keyValue) => {
const results = findName(keyValue);
if (results.length > 0) {
return results.map((item) => {
return findDependencies([...acc, ...results], item);
}).flat();
} else {
return acc;
}
}
// Starts the application by calling the fuction with the initial desired value
const newArray = findDependencies([], "Show_Everything__c");
// Check the results
console.log(newArray);
关于javascript - 使用对象在数组内部循环以获取其中一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102922/