如果我有一个指向所需属性的路径数组,如何设置为对象的属性

How do I SET to the Object's properties if I have a path array to the needed property?

本文关键字:属性 何设置 对象 设置 路径 有一个 如果 数组      更新时间:2023-09-26
var obj = {
  people: {
    John: {
      pets:{
        dog:{
          name:"Umbrella",
          age:12
        },
        cat:{
          name:"Kitty",
          age:5
        }
      }
    }
  }
};
var path=['people', 'John', 'pets', 'cat', 'name'];
var newName='Train';

如何将数组想要的内容(现在是猫的名字)设置为对象?数组可以更改,所以我不能手写。我需要一个函数来根据数组自动执行此操作

您可以使用如下所示的递归函数:

var prop = function (obj, chain) {
    if (obj && chain.length > 0) {
        return prop(obj[chain[0]], chain.slice(1));
    }
    return obj;
};
prop(obj, path);

甚至是迭代函数:

var prop = function (obj, chain) {
    var i = 0;
    while (obj && i < chain.length) {
        obj = obj[chain[i]];
        i++;
    }
    return obj;
};
prop(obj, path);

编辑:要设置一个值,您可以执行以下操作:

var set = function (obj, chain, value) {
    if (obj === undefined || obj === null) return;
    var i = 0;
    while (obj[chain[i]] !== undefined && obj[chain[0]] !== null && i < chain.length - 1) {
        obj = obj[chain[i]];
        i++;
    }
    obj[chain[i]] = value;
};
set(obj, path, 'Train');

递归使用以下函数

foreach(var key in obj)
{
console.log('key'); //gives the key name like - people, John, Pets, dog, cat etc.,
}

使用 for 循环:

var cursor = obj;
for (var i = 0, len = path.length; i < len; i++) {
    cursor = cursor[path[i]];
}