lodash找到匹配的键/嵌套键

时间:2016-04-19 08:05:12

标签: javascript momentjs lodash

我有一个带有嵌套对象的标准对象。

我正在尝试查找包含'Gmt'的所有键,并通过片刻格式化相应的纪元值。

var myObject = {
    "suffix" : "mr",
    "fname" : "jullian",
    "lname" : "exor",
    "dobGmt" : 145754294700000
    "addressLine1" : "flat 8a",
    "street" : "hoxley close",
    "rentStartedGmt" : 145754294700000,
    "deposit" : "50.00",
    "occupation" : "math teacher",
    "profession" : {
         "careerStartedGmt": 1458755224800000,
         "careerEndGmt": 1459854224800000,
     },
    "salary" : 28000,
    "votingDetail" : {
        "location" : "virgina",
        "votedOnGmt": 1874585224800000,
        "votedFor" : "world wildlife foundation"
    }
}

我可以使用标准JS循环上面的键(见下文),它会找到rentStartedGmt,但会遗漏profession.careerStartedGmtprofession.careerEndGmtvotingDetail.votedOnGmt

var myObjectClone = _.clone(myObject);

for (var key in myObjectClone) {
    if (key.indexOf("Gmt") !== -1) {

        var timeValue = myObjectClone[key];

        timeValue = timeValue.format('DD-MM-YY HH:mm:ss');

    }
}

我正在使用lodash,有什么方法可以找到包含'Gmt'的所有密钥,修改纪元,然后返回对象克隆。

更新:使用递归:

function findGmt(data) {
    for (var key in data) {
        var v = data[key];
        if (key.indexOf("Gmt") !== -1) {


        }

        if(v && typeof v === "object") {
            findGmt(v);
        }
    }
}

findGmt(myObjectClone);

1 个答案:

答案 0 :(得分:1)

不知道lodash特定的方法......

但这是vanilla js中的递归函数:

var obj = {
  "suffix": "mr",
  "fname": "jullian",
  "lname": "exor",
  "dobGmt": 145754294700000,
  "addressLine1": "flat 8a",
  "street": "hoxley close",
  "rentStartedGmt": 145754294700000,
  "deposit": "50.00",
  "occupation": "math teacher",
  "profession": {
    "careerStartedGmt": 1458755224800000,
    "careerEndGmt": 1459854224800000,
  },
  "salary": 28000,
  "votingDetail": {
    "location": "virgina",
    "votedOnGmt": 1874585224800000,
    "votedFor": "world wildlife foundation"
  }
}


function flatK(o) {
  return Object.keys(o).reduce(function(ac, x) {
    if (typeof o[x] === 'object')
      ac.push(flatK(o[x]).join());
    else
      ac.push(x);
    return ac
  }, [])
}

console.log(flatK(obj))

然后你可以过滤输出,在键中寻找'GMT'(但我会让你这样做)