如何在 JavaScript 中筛选包含对象的数组中的数组?

huangapple go评论95阅读模式
英文:

How to filter an array within array of objects in javascript?

问题

{
  "stateProvinces": [
    {
      "cities": [
        {
          "code": "T001",
          "citydescription": "Chennai"
        },
        // ...
      ],
      "statecode": "TN"
    },
    // ...
  ]
}

如果我传递州代码为TN和城市描述为Chennai,我需要以下输出:Code: T001。尝试以下方法,能够根据州过滤:

const filtervalue = getCityNames.filter((code) => {
  return code.statecode == "TN";
});
英文:

I have an array of objects containing information about cities and states. I need to filter based on statecode and citydescription properties.

{
  "stateProvinces": [
    {
      "cities": [
        {
          "code": "T001",
          "citydescription": "Chennai"
        },
        // ...
      ],
      "statecode": "TN"
    },
    // ...
  ]
}

If I pass state code as TN and city description as Chennai I need a following output: Code: T001. Tried the following and able to filter based on state:

const filtervalue = getCityNames.filter((code) => {
  return code.statecode == "TN";
});

答案1

得分: 1

一种简单的方法是使用2个find()函数。

首先查找匹配的省份,然后再查找匹配的城市。

当然,您可以使用reduce等一条命令完成这个操作,但我认为这种方法更易读:

const data = {"stateProvinces": [{"cities": [{"code": "T001","citydescription": "Chennai"}, {"code": "T002","citydescription": "Madurai"} ], "statecode": "TN"}, {"cities": [{"code": "E001","citydescription": "Erakulam"}, {"code": "M002","citydescription": "Munnar"} ], "stateCode": "KL"}]}

const findCode = 'TN';
const findCity = 'Chennai';

let res = null;

const foundProvince = data.stateProvinces.find(o => o.statecode === findCode);
if (foundProvince) {
    res = foundProvince.cities.find(c => c.citydescription === findCity)?.code;
}

console.log(res)
英文:

A straightforward way is to use 2 find()'s.

First find the matching province, then the matching city.

Of course you can do this in a single command with eg reduce, but I think this is more readable:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const data = {&quot;stateProvinces&quot;: [{&quot;cities&quot;: [{&quot;code&quot;: &quot;T001&quot;,&quot;citydescription&quot;: &quot;Chennai&quot;}, {&quot;code&quot;: &quot;T002&quot;,&quot;citydescription&quot;: &quot;Madurai&quot;} ], &quot;statecode&quot;: &quot;TN&quot;}, {&quot;cities&quot;: [{&quot;code&quot;: &quot;E001&quot;,&quot;citydescription&quot;: &quot;Erakulam&quot;}, {&quot;code&quot;: &quot;M002&quot;,&quot;citydescription&quot;: &quot;Munnar&quot;} ], &quot;stateCode&quot;: &quot;KL&quot;}]}

const findCode = &#39;TN&#39;;
const findCity = &#39;Chennai&#39;;

let res = null;

const foundProvince = data.stateProvinces.find(o =&gt; o.statecode === findCode);
if (foundProvince) {
    res = foundProvince.cities.find(c =&gt; c.citydescription === findCity)?.code;
}

console.log(res)

<!-- end snippet -->

答案2

得分: 0

从我的两个回答评论中提取翻译如下:

  1. "for a vast amount of queries on a very large data base I would suggest transforming the data structure once into a map of maps ... thus queries then would look like ... stateCodeAndCityNameBasedCityCodeMap.get('TN')?.get?.('Chennai'); ... or ... stateCodeAndCityNameBasedCityCodeMap.get('KL')?.get?.('Munnar');"

  2. "Even though a find based iteration exits early the time complexity of a nested find is much higher than a straight linear access on a Map based query path for Map is optimized for fast lookups."

请注意,这些翻译是从您提供的内容中直接提取的,没有其他额外的内容。

英文:

From my two answering comments on another answer ..

> "for a vast amount of queries on a very large data base I would suggest transforming the data structure once into a map of maps ... thus queries then would look like ... stateCodeAndCityNameBasedCityCodeMap.get(&#39;TN&#39;)?.get?.(&#39;Chennai&#39;); ... or ... stateCodeAndCityNameBasedCityCodeMap.get(&#39;KL&#39;)?.get?.(&#39;Munnar&#39;);"

> "Even though a find based iteration exits early the time complexity of a nested find is much higher then a straight linear access on a Map based query path for Map is optimized for fast lookups."

... and in order to prove the above said ...

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const stateProvinces = [{
  cities: [{
    code: &quot;T001&quot;, citydescription: &quot;Chennai&quot;,
  }, {
    code: &quot;T002&quot;, citydescription: &quot;Madurai&quot;,
  }],
  statecode: &quot;TN&quot;,
}, {
  cities: [{
    code: &quot;E001&quot;, citydescription: &quot;Erakulam&quot;,
  }, {
    code: &quot;M002&quot;, citydescription: &quot;Munnar&quot;,
  }],
  statecode: &quot;KL&quot;,
}];

const stateCodeAndCityNameBasedCityCodeMap = new Map(
  stateProvinces.map(({ statecode, cities }) =&gt; [
    statecode,
    new Map(
      cities.map(({ citydescription, code }) =&gt; [ citydescription, code ])
    )
  ])
);
console.log(
  stateCodeAndCityNameBasedCityCodeMap.get(&#39;TN&#39;)?.get?.(&#39;Chennai&#39;)
);
console.log(
  stateCodeAndCityNameBasedCityCodeMap.get(&#39;KL&#39;)?.get?.(&#39;Munnar&#39;)
);
console.log(
  stateCodeAndCityNameBasedCityCodeMap.get(&#39;KL&#39;)?.get?.(&#39;FOO&#39;)
);
console.log(
  stateCodeAndCityNameBasedCityCodeMap.get(&#39;BAR&#39;)?.get?.(&#39;BAZ&#39;)
);

<!-- language: lang-css -->

.as-console-wrapper { min-height: 100%!important; top: 0; }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月4日 21:45:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定