可以使用递归函数来按路径设置对象中的值并展平包含对象和数组的对象数组。以下是代码示例:
/**
* 按路径设置对象中的值
* @param {Object} obj - 要设置值的对象
* @param {Array} path - 属性路径数组
* @param {*} value - 要设置的值
* @param {Number} index - 路径数组的索引值(递归使用)
* @returns {Object} - 返回已设置值的对象
*/
function setValueByPath(obj, path, value, index = 0) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const prop = path[index];
if (index === path.length - 1) {
obj[prop] = value;
} else {
obj[prop] = setValueByPath(obj[prop], path, value, index + 1);
}
return obj;
}
/**
* 展平包含对象和数组的对象数组
* @param {Object[]} arr - 要展平的数组
* @returns {Object[]} - 返回展平后的数组
*/
function flattenObjects(arr) {
return arr.reduce((acc, obj) => {
const isArray = Array.isArray(obj);
const entries = isArray ? obj.map((el) => [null, el]) : Object.entries(obj);
const objArr = entries.map(([key, val]) => [
isArray ? null : key,
typeof val !== 'object' || val === null ? val : flattenObjects([val]),
]);
return acc.concat(objArr);
}, []);
}
// 示例代码
const data = {
name: 'John Doe',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA',
zip: '12345',
},
phones: [
{
type: 'home',
number: '555-1234',
},
{
type: 'work',
number: '555-5678',
},
],
};
console