简体   繁体   中英

Javascript: Extracting values from json where key equals string

I have a complex nested json and I need to extract values where the key equals matches a string that I provide. I need these values to be returned in as a single array.

How can I implement this? Or, are there any frameworks or utilities I can use to do so?

The data set that I am trying to extract values from is quite large, so I have provided a snippet below to give an idea of what I'm working with:

{
  "_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
        }
      ]
    }
  ]
}

From the data above, I would like to get an array ["form", "foo"] for the key type .

If you wanted to avoid adding a library or dependency to your project just for this, you could implement a recursive value extraction function to achieve what you need like so:

 // 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")) 

Damn beaten to it :)

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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM