0

i want to make a system that searches for data in json. so i have the json on an rest api. the api looks like this

[
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
]

there are alot of values with the same name.

i googled alot to find some awnsers but they all say i need to number. data.value[1]

i want to be able to search for patty and get the info & type just get the json data

Javascript or nodeJS

1 Answers1

0

If you know both the key and the value, it seems this is the simplest way:

const arrayOfObjects = [
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
];

const key = 'name';
const value = 'patty';
const object = arrayOfObjects.find(obj => obj[key] === value);

console.log(object);

If you do not know the key, this is a possible way:

const arrayOfObjects = [
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
];

const value = 'patty';
const object = arrayOfObjects.find(
  obj => Object.values(obj).some(val => val === value)
);

console.log(object);
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26