Here i m given some data in Json formate. I want to fillter it with it atrribute .
[
{
"_id": "1",
"name": "ShalimarBhagh",
"city_id": "1",
"location_id": "1",
"country_name": "India"
},
{
"_id": "2",
"name": "Janpat, Delhi",
"city_id": "1",
"location_id": "2",
"country_name": "India"
},
{
"_id": "3",
"name": "MSP, Delhi",
"city_id": "1",
"location_id": "3",
"country_name": "India"
},
{
"_id": "4",
"name": "MSP, Pune",
"city_id": "2",
"location_id": "4",
"country_name": "India"
},
{
"_id": "5",
"name": "Anand Pur",
"city_id": "1",
"location_id": "5",
"country_name": "India"
},
]
From the Above Json file just want to display only those object which has arrtibute with that value ( name:"Delhi")
it Should be Displayed like that by using node.js and React
{
"_id": "2",
"name": "Janpat, Delhi",
"city_id": "1",
"location_id": "2",
"country_name": "India"
},
{
"_id": "3",
"name": "MSP, Delhi",
"city_id": "1",
"location_id": "3",
"country_name": "India"
},
CodePudding user response:
You can use the filter function. If the array is named arr then
var new_array = arr.filter(function callback(element, index, array) { return (element.name.includes("Delhi")) });
//new_array is the filtered array.
CodePudding user response:
Just use array's filter method:
const data = [
{
_id: "1",
name: "ShalimarBhagh",
city_id: "1",
location_id: "1",
country_name: "India",
},
{
_id: "2",
name: "Janpat, Delhi",
city_id: "1",
location_id: "2",
country_name: "India",
},
{
_id: "3",
name: "MSP, Delhi",
city_id: "1",
location_id: "3",
country_name: "India",
},
];
const filtered = data.filter((item) =>
item.name.toLowerCase().includes("delhi")
);
console.log(filtered);
CodePudding user response:
Let's say your array is stored in a variable called elements
.
What you can do is filter
all of the elements with a condition that the name
includes
string "Delhi"
const elements = [
{
"_id": "1",
"name": "ShalimarBhagh",
"city_id": "1",
"location_id": "1",
"country_name": "India"
},
{
"_id": "2",
"name": "Janpat, Delhi",
"city_id": "1",
"location_id": "2",
"country_name": "India"
},
{
"_id": "3",
"name": "MSP, Delhi",
"city_id": "1",
"location_id": "3",
"country_name": "India"
},
{
"_id": "4",
"name": "MSP, Pune",
"city_id": "2",
"location_id": "4",
"country_name": "India"
},
{
"_id": "5",
"name": "Anand Pur",
"city_id": "1",
"location_id": "5",
"country_name": "India"
}];
const result = elements.filter(element => element.name.includes("Delhi"));
console.log(result);
Now result
contains all elements whose name includes Delhi. Note that this does not modify the original array, instead it returns a new array.