在对象中查找匹配的属性名称并返回其值

时间:2014-06-20 04:37:04

标签: javascript node.js

我有一个未知的结构化JSON对象,我想读取它的所有属性,并在条件匹配时返回它的值。

{
      "tags": ["a", "b", "c"],
      "image": "path/to/thumbnail.png",
      "description": "First level description",
      "name": "First name",
      "another": {
        "abcde": {
          "label": "one two three",
          "description": "Oopsy!"
        },
        "fghijk": {
          "label": "Label ABC :)",
          "description": "Is not a song here bruh!"
        }
      },
      "couldBeEmpty": {},
      "couldBeLast": {
        "someCoolName": {
          "label": "Some label here you know",
          "description": "Another Desc Again",
          "type": "text"
        },
        "someLabelAgain": {
          "label": "Just a label name",
          "description": "Yep another Desc :)",
          "type": "color"
        },
        "someObjLabel": {
          "label": "Another label name",
          "description": "Desc label here too",
          "type": "text"
        },
        "ahCoolThing": {
          "label": "Some label for this too",
          "description": "Desc here is fine too",
          "type": "color"
        },
        "couldBeLastInHere": {
          "label": "label",
          "description": "Desc goes here",
          "type": "color"
        }
      }
    }

我希望获得对象的任何给定结构的所有名称标签描述,然后使新对象成为某种东西像这样

{
  "description": "First level description",
  "name": "First name",
  "abcde/label": "one two three",
  "abcde/description": "Oopsy!"
  "fghijk/label": "Label ABC :)",
  "fghijk/description": "Is not a song here bruh!"
  "someCoolName/label": "Some label here you know",
  "someCoolName/description": "Another Desc Again",
  "someLabelAgain/label": "Just a label name",
  "someLabelAgain/description": "Yep another Desc :)",
  "someObjLabel/label": "Another label name",
  "someObjLabel/description": "Desc label here too",
  "ahCoolThing/label": "Some label for this too",
  "ahCoolThing/description": "Desc here is fine too",
  "couldBeLastInHere/label": "label",
  "couldBeLastInHere/description": "Desc goes here"
}

现在我尝试使用Lodash,但无法找到找到具有给定名称的所有属性的方法,除非必须遍历所有内容

1 个答案:

答案 0 :(得分:2)

您正在寻找的内容本质上是一种自定义缩减功能(您尝试将对象缩减为其数据的某些压缩表示)。这是一个允许您指定要删除的字段的实现:

function myReduce(o, fields, p, c) {
    // p: path
    // c: context (accumulator)
    if(p===undefined) p = '', c = {};
    for(var prop in o) {
        if(!o.hasOwnProperty(prop)) continue;
        if(fields.indexOf(prop)!=-1) c[p + prop] = o[prop];
        else if(typeof o[prop]==='object') myReduce(o[prop], fields, prop + '/', c);
    }
    return c;
}

要获得您感兴趣的字段,您可以这样称呼它:

myReduce(data, ['name', 'label', 'description']);