Javascript:从json中提取值,其中键等于字符串

时间:2018-12-17 18:55:53

标签: javascript

我有一个复杂的嵌套json,我需要提取[]proyecto等于我提供的字符串的值。我需要将这些值作为单个数组返回。

我该如何实现?或者,我可以使用任何框架或实用程序吗?

我要从中提取值的数据集非常大,因此我在下面提供了一个代码段,以使我对正在使用的内容有所了解:

key

从上面的数据中,我想获得键{ "_id": "5c12bd254c25881cb850fcad", "type": "form", "tags": [ "isf" ], "owner": "5c0050319597940268f8ae7a", "components": [ { "clearOnHide": false, "key": "customerInformationPanel", "input": false, "title": "Customer's Information", "theme": "default", "type" : "foo", "tableView": false, "components": [ { "autofocus": false } ] } ] } 的数组["form", "foo"]

2 个答案:

答案 0 :(得分:2)

如果您要避免为此而在项目中添加库或依赖项,则可以实现递归值提取功能以实现所需的功能:

// Recusrivly extracts values for key, from input object
function extractValues(input, key) {

  let result = []

  if (input) {
    
    // If value exists for key on current input object, add it to result
    let keyValue = input[key]
    if (keyValue !== undefined) {
      result.push(keyValue);
    }

    // Iterate object or array value types on input and recusrivly extract
    // values from same key from those "child" values if these exist
    for (const value of Object.values(input)) {

      if (typeof value === 'object') {
        result = result.concat(extractValues(value, key))
      } else if (typeof value === 'array') {
        for (const item of value) {
          result = result.concat(extractValues(item, key))
        }
      }
    }

  }
  return result
}

const data = {"_id":"5c12bd254c25881cb850fcad","type":"form","tags":["isf"],"owner":"5c0050319597940268f8ae7a","components":[{"clearOnHide":false,"key":"customerInformationPanel","input":false,"title":"Customer's Information","theme":"default","tableView":false,"components":[{"autofocus":false,"input":true,"tableView":true,"inputType":"text","inputMask":"","label":"Name","key":"customerName","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true},{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"","label":"Address","key":"customerAddress","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true},{"clearOnHide":false,"label":"Columns","input":false,"tableView":false,"key":"columns4","columns":[{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"","label":"City","key":"customerCity","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true}],"width":5,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"label":"State","key":"customerState","placeholder":"","data":{"values":[{"value":"","label":""}],"json":"","resource":"","custom":"","headers":[{"value":"","key":""}]},"dataSrc":"url","valueProperty":"abbreviations","defaultValue":"","refreshOn":"","filter":"","authenticate":false,"template":"<span>{{ item.name }}</span>","multiple":false,"protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"validate":{"required":false},"type":"select","labelPosition":"top","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"selectValues":"result","lockKey":true}],"width":4,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"99999","label":"Zip","key":"customerZip","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true}],"width":3,"offset":0,"push":0,"pull":0}],"type":"columns","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"hideLabel":true},{"clearOnHide":false,"label":"Columns","input":false,"tableView":false,"key":"columns3Columns","columns":[{"components":[{"autofocus":false,"input":true,"tableView":false,"label":"Date of Birth","key":"customerDateOfBirth","fields":{"day":{"type":"number","placeholder":"","required":false},"month":{"type":"select","placeholder":"","required":false},"year":{"type":"number","placeholder":"","required":false}},"dayFirst":false,"protected":false,"persistent":true,"hidden":false,"clearOnHide":true,"validate":{"custom":""},"type":"day","labelPosition":"top","inputsLabelPosition":"bottom","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"lockKey":true,"hideLabel":false}],"width":4,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"label":"Sex","key":"customerSex","placeholder":"","data":{"values":[{"value":"male","label":"Male"},{"value":"female","label":"Female"}],"json":"","url":"","resource":"","custom":""},"dataSrc":"values","valueProperty":"","defaultValue":"","refreshOn":"","filter":"","authenticate":false,"template":"<span>{{ item.label }}</span>","multiple":false,"protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"validate":{"required":false},"type":"select","labelPosition":"top","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"lockKey":true}],"width":4,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"tel","inputMask":"(999) 999-9999","label":"Cell Phone","key":"claimantCellPhone","placeholder":"","prefix":"","suffix":"","multiple":false,"protected":false,"unique":false,"persistent":true,"hidden":false,"defaultValue":"","clearOnHide":true,"validate":{"required":false},"type":"phoneNumber","labelPosition":"top","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"lockKey":true}],"width":4,"offset":0,"push":0,"pull":0}],"type":"columns","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"hideLabel":true}],"type":"panel","breadcrumb":"default","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"label":"panel4","hideLabel":false,"lockKey":true},{"clearOnHide":false,"key":"panel7","input":false,"title":"Witness","theme":"default","tableView":false,"components":[{"input":true,"tree":true,"components":[{"clearOnHide":false,"label":"Columns","input":false,"tableView":false,"key":"columns7","columns":[{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"","label":"Name","key":"witnessName","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true}],"width":6,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"tel","inputMask":"(999) 999-9999","label":"Cell Phone","key":"witnessCellPhone","placeholder":"","prefix":"","suffix":"","multiple":false,"protected":false,"unique":false,"persistent":true,"hidden":false,"defaultValue":"","clearOnHide":true,"validate":{"required":false},"type":"phoneNumber","labelPosition":"top","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"lockKey":true}],"width":6,"offset":0,"push":0,"pull":0}],"type":"columns","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"hideLabel":true},{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"","label":"Address","key":"witnessAddress","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true},{"clearOnHide":false,"label":"Columns","input":false,"tableView":false,"key":"columns6","columns":[{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"","label":"City","key":"witnessCity","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true}],"width":5,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"label":"State","key":"witnessState","placeholder":"","data":{"values":[{"value":"","label":""}],"json":"","resource":"","custom":"","headers":[{"value":"","key":""}]},"dataSrc":"url","valueProperty":"abbreviations","defaultValue":"","refreshOn":"","filter":"","authenticate":false,"template":"<span>{{ item.name }}</span>","multiple":false,"protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"validate":{"required":false},"type":"select","labelPosition":"top","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"selectValues":"result","lockKey":true}],"width":4,"offset":0,"push":0,"pull":0},{"components":[{"autofocus":false,"input":true,"tableView":false,"inputType":"text","inputMask":"99999","label":"Zip","key":"witnessZip","placeholder":"","prefix":"","suffix":"","multiple":false,"defaultValue":"","protected":false,"unique":false,"persistent":true,"hidden":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":"","customPrivate":false},"conditional":{"show":"","when":null,"eq":""},"type":"textfield","labelPosition":"top","tags":[],"properties":{},"lockKey":true}],"width":3,"offset":0,"push":0,"pull":0}],"type":"columns","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"hideLabel":true},{"autofocus":false,"input":true,"tableView":false,"label":"Observed Caused of Incident","key":"witnessesObservedCausedOfIncident","placeholder":"","prefix":"","suffix":"","rows":3,"multiple":false,"defaultValue":"","protected":false,"persistent":true,"hidden":false,"wysiwyg":false,"clearOnHide":true,"spellcheck":true,"validate":{"required":false,"minLength":"","maxLength":"","pattern":"","custom":""},"type":"textarea","labelPosition":"top","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"lockKey":true}],"multiple":false,"tableView":false,"label":"Witnesses","key":"witnesses","protected":false,"persistent":true,"hidden":false,"clearOnHide":true,"templates":{"header":"<div class=\"row\"> \n  {% util.eachComponent(components, function(component) { %}\n    <div class=\"col-sm-2\"> \n      {{ component.label }} \n    </div> \n  {% }) %} \n</div>","row":"<div class=\"row\"> \n  {% util.eachComponent(components, function(component) { %}\n    <div class=\"col-sm-2\"> \n      {{ getView(component, row[component.key]) }} \n    </div> \n  {% }) %} \n  <div class=\"col-sm-2\"> \n    <div class=\"btn-group pull-right\"> \n      <div class=\"btn btn-default editRow\">Edit</div> \n      <div class=\"btn btn-danger removeRow\">Delete</div> \n    </div> \n  </div> \n</div>","footer":""},"type":"editgrid","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"lockKey":true}],"type":"panel","breadcrumb":"default","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{},"label":"panel7","hideLabel":false},{"autofocus":false,"input":true,"label":"Submit","tableView":false,"key":"submit","size":"md","leftIcon":"","rightIcon":"","block":false,"action":"submit","disableOnInvalid":false,"theme":"primary","type":"button","tags":[],"conditional":{"show":"","when":null,"eq":""},"properties":{}}],"display":"form","submissionAccess":[{"roles":[],"type":"create_all"},{"roles":["5c004f33e89a0503401d1a60","5c004f33e89a0503401d1a61"],"type":"read_all"},{"roles":["5c004f33e89a0503401d1a60"],"type":"update_all"},{"roles":["5c004f33e89a0503401d1a60"],"type":"delete_all"},{"roles":["5c004f33e89a0503401d1a61"],"type":"create_own"},{"roles":[],"type":"read_own"},{"roles":[],"type":"update_own"},{"roles":[],"type":"delete_own"}],"title":"Incidents - Customers","name":"incidentsCustomers","path":"isf/workerscompcustomers","access":[{"roles":["5c004f33e89a0503401d1a60","5c004f33e89a0503401d1a61","5c004f33e89a0503401d1a62"],"type":"read_all"}],"created":"2018-12-13T20:12:21.662Z","modified":"2018-12-14T21:12:02.784Z","machineName":"workersCompCustomers"}

console.log("values for key 'roles':", extractValues(data, "roles"))
console.log("values for key 'type':", extractValues(data, "type"))
console.log("values for key 'foo':", extractValues(data, "foo"))

答案 1 :(得分:1)

该死的被殴打:)

var findInObject = function(dataObj, key) {
  let arr = [];
  if(typeof dataObj !== 'object') return arr;
  for(let prop in dataObj) {
    console.log("Found Property: " + prop);
    if(prop == key) {
      console.log("Match");
      console.log("Current Array Length: " + arr.length);
      arr.push(dataObj[key]);
    } else {
      if(Array.isArray(dataObj[prop])) {
        console.log("Array found: " + prop);
        dataObj[prop].forEach((item) => {
          arr = arr.concat(findInObject(item, key));
        });

      }
    }
  }
  return arr;
}

console.log(findInObject(data, 'key'));