可以使用递归和迭代的方式来实现。以下是两种常见的方法:
function extractValue(objArray, key) {
let result = [];
for (let i = 0; i < objArray.length; i++) {
if (typeof objArray[i] === 'object') {
result = result.concat(extractValue(objArray[i], key));
} else if (objArray[i] === key) {
result.push(objArray[i]);
}
}
return result;
}
// 示例用法
const data = [
{ id: 1, name: 'John', children: [{ id: 2, name: 'Alice' }] },
{ id: 3, name: 'Bob', children: [{ id: 4, name: 'Charlie' }] }
];
const result = extractValue(data, 'name');
console.log(result); // 输出:['John', 'Alice', 'Bob', 'Charlie']
function extractValue(objArray, key) {
let result = [];
const stack = [...objArray];
while (stack.length) {
const item = stack.pop();
if (typeof item === 'object') {
for (let prop in item) {
stack.push(item[prop]);
}
} else if (item === key) {
result.push(item);
}
}
return result;
}
// 示例用法
const data = [
{ id: 1, name: 'John', children: [{ id: 2, name: 'Alice' }] },
{ id: 3, name: 'Bob', children: [{ id: 4, name: 'Charlie' }] }
];
const result = extractValue(data, 'name');
console.log(result); // 输出:['John', 'Alice', 'Bob', 'Charlie']
这两种方法都可以从嵌套对象数组中提取指定的值。递归方法适用于嵌套层级较深的情况,而迭代方法适用于嵌套层级较浅的情况。根据实际情况选择合适的方法。
推荐的腾讯云相关产品:腾讯云云函数(Serverless Cloud Function),它是一种无服务器计算服务,可以在云端运行代码,无需关心服务器的配置和管理。您可以使用云函数来处理和提取嵌套对象数组中的值。了解更多信息,请访问腾讯云云函数产品介绍页面:腾讯云云函数。
领取专属 10元无门槛券
手把手带您无忧上云