I have the following dataset:
var data = [
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710653,
"key": "test_key1"
},
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710654,
"key": "test_key2"
},
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710655,
"key": "test_key3"
},
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710656,
"key": "test_key4"
}]
I need to be able to search through this array and return the key where the ID is equal to a certain ID.
For example, I need the object keys where ID = 360000710654 OR ID = 360000710655.
Therefore, pseudo code =
ID = 360000710654 OR ID = 360000710655 would return:
key: "test_key2",
key: "test_key3"
This is a small example, but I will need this to work on much larger datasets with about 40 different IDs that I need to pull the key from. In addition, finding a way to change the key name for the key/value pair would be great so I could easily identify which key is what.
I have tried making this work with a JS filter function, as I cannot use any outside functions but have been unsuccessful so far. I am stuck and unsure where to take this and would love some additional help.
I tried this but my output is always null.
var data = [{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710653,
"key": "test_key1"
},
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710654,
"key": "test_key2"
},
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710655,
"key": "test_key3"
},
{
"raw_title": "Test A",
"raw_description": "Description",
"url": "test_url",
"id": 360000710656,
"key": "test_key4"
}
];
var result = data.filter(obj => {
return obj.id === 360000710654;
});
console.log(result);
This works, and returns the data in the order it is found.
let data = data
.filter(item => [360001060233, 360000710653].includes(item.id))
.map(item => item.key)
return data;
Update
I am trying to have it return in the order I search for it.
This snippet is based on the comments to the answer from Mr. Polywhirl:
const keysForIds = (ids, data) =>
Object.fromEntries(
ids .map ((target, _, __, item = data. find (({id}) => id == target) || {}) => [target, item.key]
))
const data = [{"id": 360000710653, "key": "test_key1", "raw_description": "Description", "raw_title": "Test A", "url": "test_url"}, {"id": 360000710654, "key": "test_key2", "raw_description": "Description", "raw_title": "Test A", "url": "test_url"}, {"id": 360000710655, "key": "test_key3", "raw_description": "Description", "raw_title": "Test A", "url": "test_url"}, {"id": 360000710656, "key": "test_key4", "raw_description": "Description", "raw_title": "Test A", "url": "test_url"}]
console .log (
keysForIds([360000710654, 360000710658, 360000710655], data)
)