如何在传递对象和键并获取嵌套对象的值的地方创建函数

时间:2019-07-03 10:36:07

标签: javascript

我有一个嵌套的对象,我该如何传递传入该对象的函数和一个键并取回值?

示例输入

object = {"a1":{"b1":"{"c1":"d1"}"}}
key = a1/b1/c1
object = {"x1":{"y1":"{"z1":"a1"}"}}
key = x1/y1/z1
value = a1

下面是我尝试过的,但这是错误的

var obj, traverse;

obj = {
  a1: {
    b1: c1,
    b1: d1
  },
  x1: {
    y1: z1,
    y1: a1
  }
};

traverse = function(node, path) {
  var pairs;
  if (!(pairs = _(node).pairs()).length) {
    return [
      {
        keys: path,
        value: node
      }
    ];
  } else {
    return [].concat.apply([], _(pairs).map(function(kv) {
      return traverse(kv[1], path.concat(kv[0]));
    }));
  }
};

console.log(traverse(obj, []));

3 个答案:

答案 0 :(得分:0)

您可以尝试lodash _.get,这种访问方式非常出色:

很好的是,如果找不到该路径,您可以传递默认值。

var object = {"a1": { "b1": { "c1": "d1" }}};

console.log("Result at 'a1.b1.c1': ",_.get(object, 'a1.b1.c1'));
console.log("Result at 'a1.b1.nonexistent key': ",_.get(object, 'a1.b1.nonexistent', "default result"));

var object2 = {"x1":{"y1":{"z1":"a1"}}};
console.log("Result at 'x1.y1.z1': ",_.get(object2, 'x1.y1.z1'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

答案 1 :(得分:0)

如果可以将键表示为数组,则可以使用reduce解决此问题:

const obj = {"x1":{"y1":{"z1":"a1"}}}

const keys = ['x1', 'y1', 'z1']


const value = keys.reduce((acc,key)=>acc[key], obj)// "a1"

作为接受键数组或'x1.y1.z1'形式的字符串的函数,后退表示未定义的值:

const getValueFromKeys = (obj, keys, defaultValue)=> (Array.isArray(keys)?keys:keys.split('.')).reduce((acc,key)=>acc[key] || defaultValue, obj)

答案 2 :(得分:0)

let obj = {
    a1: {
        b1: {
            nested: true
        },
    },
    x1: {
        y1: 'zl',
    }
};


function getObjectKeys(object, key) {
    // if you want another split key you can change this.
    const keys = key.split('.');
    let obj = object;
    for (let ikey of keys) {
        for (let [objKey, value] of Object.entries(obj)) {
            if(!keys.includes(objKey)) {
                continue;
            }
            obj = value;
        }
    }
    return obj;
}

console.log(getObjectKeys(obj, 'a1.b1.nested'));

console.log(getObjectKeys(obj, 'x1.y1'));
// even if there is another additional key
console.log(getObjectKeys(obj, 'x1.y1.nested'));

不使用任何库, 了解有关Object.entries

的更多信息