简体   繁体   English

反应提取嵌套的 json object

[英]React extracting a nested json object

How can I extract the 'jobs' object from a nested json list like this:如何从嵌套的 json 列表中提取“作业” object,如下所示:

result:
{
 person:
  [
    {
       name: ""
       address: ""
       jobs: [
         {
           company:""
          },
          {
            company:""
           }
         ]
       }
      ]
     }

Thank you谢谢

Write a generic method to extract object properties.编写一个通用方法来提取 object 属性。

function onExtract(key, data) {
  if (isObject(data)) {
    for (let item in data) {
      if (key === item) {
        return data[item];
      }
      const res = onExtract(key, data[item]);
      if (res !== null) return res;
    }
  }
  if (isArray(data)) {
    for (let item of data) {
      const res = onExtract(key, item);
      if (res !== null) return res;
    }
  }
  return null;
}

function isObject(obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}
function isArray(arr) {
  return Object.prototype.toString.call(arr) === "[object Array]";
}


// test
const data = {
  person: [
    {
      name: "",
      address: "",
      jobs: [
        {
          company: ""
        },
        {
          company: ""
        }
      ]
    }
  ]
};

console.log(onExtract("jobs", data));

let's say you have a return var that contains this json value假设您有一个包含此 json 值的返回变量

let mappedCompanies = return.person.map(person => 
     person.jobs.map(job => job.company)
).flatMap(m => m)

mappedCompanies would contain an array with all the companies names for each one of the registers in "person", all as one array of strings mappedCompanies将包含一个数组,其中包含“person”中每个寄存器的所有公司名称,全部作为一个字符串数组

you can read more about Array.map() here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map您可以在此处阅读有关 Array.map() 的更多信息: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map

A dynamic way to query the person[] and find jobs, is to use the javascript map() method.查询person[]和查找工作的动态方法是使用 javascript map()方法。

Here is the code without comments.这是没有注释的代码。

  const personsJobs = (personName, personAddress) => {
    const jobs = result.person.map((el) => {
        if (el.name === personName && el.address === personAddress) {
          return el.jobs;
        } else {
          return null;
        }
      })
      .filter((el) => el !== null);

    return jobs;
  };

  console.log(personsJobs("wyatt", "1234 test ln"));

Here is the code with comments to explain how the personsJob function works.这是带有注释的代码,用于解释personsJob function 的工作原理。


// Blow is an ES6 arrow function with the parameters 'personName' and 'personAddress',
// which represents the person in which you are querying for jobs (using both a persons 
// name and address so in the case of persons with the same name, you only find the jobs
// of the person you want).

  const personsJobs = (personName, personAddress) => {

// Since 'person' is an array, we can use the 'map' method as stated before, which 
// will create a new array (jobs) that will store the jobs a specific person has.

    const jobs = result.person.map((el) => {

// el stands for the current position in the person array. 
// if el's (the current person) name and address values are equal to that of the 
// parameters personName and personAddress, then that persons jobs are added to the jobs // array, however, if el does not satisfy the two parameters, null is added to the jobs
// array.
// The array, upon completion, will look something like this: ["programmer", null, null]

        if (el.name === personName && el.address === personAddress) {
          return el.jobs;
        } else {
          return null;
        }
      })

// Finally, the filter method is called to remove all null values so that you will
// only have the persons job in the jobs array.
// After filtering, the array will look like this: ["programmer"]

      .filter((el) => el !== null);

    return jobs;
  };

// Prints the array of wyatt's jobs

  console.log(personsJobs("wyatt", "1234 test ln"));

So, following the conclusion of the function, you will have dynamically found the jobs of a specific person.因此,在 function 的结论之后,您将动态找到特定人员的工作。

you can use flatMap function like:你可以使用 flatMap function 像:

 const jobsData = result.person.flatMap(item => item.jobs);

Here is a flexible solution using object-scan这是使用对象扫描的灵活解决方案

 // const objectScan = require('object-scan'); const data = { person: [{ name: '', address: '', jobs: [{ company: '' }, { company: '' }] }] }; console.log(objectScan(['person[*].jobs'], { reverse: false, rtn: 'value' })(data)); // => [ [ { company: '' }, { company: '' } ] ]
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/object-scan@14.0.0"></script>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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