Skip to content
Advertisement

node.js find attributes with same value in multiple JSON files

Hey I would like to ask if it is possible to find lets say in 10 JSON files which are looking like this:

1.json:

{
  "name": "Miami",
  "attributes": [
    {
      "att_type": "People",
      "value": "1000"
    },
    {
      "att_type": "Cars",
      "value": 300
    }
  ]
}

2.json:

{
  "name": "New York",
  "attributes": [
    {
      "att_type": "People",
      "value": "5000"
    },
    {
      "att_type": "Cars",
      "value": 900
    }
  ]
}

And so on… just different attribute values. Lets say I want to find only towns with People > 2500 and I’m not even sure if it is possible or do I need to upload the json files to some database perhaps?

Thank you.

Advertisement

Answer

const data = [{
    "name": "Miami",
    "attributes": [{
        "att_type": "People",
        "value": "1000"
      },
      {
        "att_type": "Cars",
        "value": 300
      }
    ]
  },
  {
    "name": "New York",
    "attributes": [{
        "att_type": "People",
        "value": "5000"
      },
      {
        "att_type": "Cars",
        "value": 900
      }
    ]
  }
]

const result = data
  // find cities with attribute `People` with value greater than 2500
  .filter(d => +d.attributes.find(attr => attr.att_type === 'People').value > 2500)
  // get name of the city
  .map(d => d.name)

console.log(result)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement