Javascript-迭代嵌套对象,获取值和链接的键 [英] Javascript- Iterate over nested objects, getting values and chained keys

查看:70
本文介绍了Javascript-迭代嵌套对象,获取值和链接的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有对象:

Nested1: {
    "nested21": {
        "nested31": {
            value: "im sooo nested"
        } ,
        "nested32": {
            value: "im sooo nested"
        }
    },
    "nested22": {
        "nested31": {
            value: "im sooo nested"
        } ,
        "nested32": {
            value: "im sooo nested"
        }
    }
}

在可能存在不确定数量的嵌套对象的地方,我想得到类似的东西:

Where there can be an undefined number of nested objects, i'd like to get something like:


Nested1.nested21.nested31 - im sooo nested
Nested1.nested21.nested32 - im sooo nested

依此类推

我正在考虑一个递归函数,但是如何将链接的键保留在内存中?

I'm thinking of a recursive function but how to keep in memory the chained keys ?

推荐答案

知道了

var obj, traverse;

obj = {
  a: {
    b: 1,
    c: 2
  },
  d: {
    e: 3,
    f: 4
  }
};

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, []));

这篇关于Javascript-迭代嵌套对象,获取值和链接的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆