Imagine having a JSON array structured like this
[{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]
The goal is to extract an array consisting of all the name
s with the website
value set to google
.
To filter the JSON array and keep only the entries where the website
is google
, one can use the following code:
var data_filter = data.filter( element => element.website =="google");
console.log(data_filter);
Running the above code yields the following output:
[{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"}]
The next step involves extracting the name
values into a separate array. Attempting this, I tried:
let new_array = [];
new_array.push(data_filter.body.name)
However, it resulted in an undefined error for name
. Other attempts included:
new_array.push(data_filter.name)
new_array.push(data_filter.body[0].name)
Unfortunately, none of these approaches yielded the desired outcome. What might be missing from my approach?
For reference on working with JSON data and filtering methods, see this related discussion on Stack Overflow: post - credit to the original poster and contributors.