Reputation: 830
I simply want to know how to return the indexes of the objects whose name property is equal to "Bob" using the filter method. (in this case one Index for simplicity)
data.json
[
{
"index": "14",
"name": "Bob",
"age": "23",
},
{
"index": "23",
"name": "John",
"age": "30",
},
{
"index": "17",
"name": "Bob",
"age": "25",
},
]
app.js
const data = require("./data.json");
const searchword = "Bob";
const result = data.filter((word) => ???word === searchword???);
console.log(result);
Should show index:14,17
Upvotes: 0
Views: 108
Reputation: 11001
Using reduce
method
const data = [
{
index: "14",
name: "Bob",
age: "23",
},
{
index: "23",
name: "John",
age: "30",
},
{
index: "17",
name: "Bob",
age: "25",
},
];
const getIndexes = (arr, word) =>
arr.reduce(
(acc, { index, name }) => (name === word ? acc.concat(index) : acc),
[]
).toString();
console.log(getIndexes(data, "Bob"));
Upvotes: 0
Reputation: 136104
This is as simple as a filter
and a map
const data = [
{
"index": "14",
"name": "Bob",
"age": "23",
},
{
"index": "23",
"name": "John",
"age": "30",
},
{
"index": "17",
"name": "Bob",
"age": "25",
},
]
const searchWord = "Bob";
const result = data.filter(x => x.name == searchWord) // find by searchWord
.map(x => x.index); // get the index
console.log(result.join(",")); // result is an array
Upvotes: 1