Retrieve all matching values from json array - javascript

I have a json array. I want to retrieve all "tag" values where listid=n;
[
{"listid":"1","tag":"ONE"},
{"listid":"1","tag":"TWO"},
{"listid":"1","tag":"THREE"},
{"listid":"2","tag":"ONE"},
{"listid":"2","tag":"TWO"},
{"listid":"2","tag":"THREE"},
{"listid":"2","tag":"FOUR"},
{"listid":"3","tag":"ONE"},
{"listid":"3","tag":"FOUR"},
{"listid":"3","tag":"TWO"},
{"listid":"3","tag":"SIX"},
{"listid":"3","tag":"FIVE"},
{"listid":"3","tag":"THREE"}
]
I have found how to search an array for an individual value, but I can't seem to find anything on returning multiple values I require, as a json array.

You can first filter for the items you want, then map to get the specific property you are after.
let a = [
{"listid":"1","tag":"ONE"},
{"listid":"1","tag":"TWO"},
{"listid":"1","tag":"THREE"},
{"listid":"2","tag":"ONE"},
{"listid":"2","tag":"TWO"},
{"listid":"2","tag":"THREE"},
{"listid":"2","tag":"FOUR"},
{"listid":"3","tag":"ONE"},
{"listid":"3","tag":"FOUR"},
{"listid":"3","tag":"TWO"},
{"listid":"3","tag":"SIX"},
{"listid":"3","tag":"FIVE"},
{"listid":"3","tag":"THREE"}
]
let n = "2"
let found = a.filter(item => item.listid === n).map(item => item.tag)
console.log(found)
This is assuming you want to do this in javascript

Related

JavaScript Objects filtering out specific property names

I am creating a filter for a diagram. Whenever a filter is clicked it should remove that category from the diagram. The api call returns an object with names. let’s say the object returns 40 items and I want to filter 5 out by name. What is the best way to approach this?.
I tried to manually type the property names into an array and run the .filter on my object like below. However it returns the entire object unfiltered.
filterDiagram() {
Const array = [“all the names of the properties I want to filter out”]
carbonates = array.forEach(x) => {console.log(x)}
Const filterCat = data.filter (io =>
io.name !== carbonates)
}
Let's say, the array consists of all the names/categories you want to take out.
const toBetakenOut = ['fruits','salts', 'etc' ]
// Please make sure they are not 1 string but rather comma-separated values.
You can filter the API data by using the filter function on the data,to remove objects with names that are within toBetakenOut.
const filterCat = data.filter (io => !toBetakenOut.includes(io.name))
function filterDiagram(){
const dontWantsArray = [/*all of the things you dont want*/];
// Outputs an array of keys
const filteredKeys = Object.keys(yourJSObject)
.filter(key => !dontWantsArray.includes(key));
// After you found the keys you can get the values to another array by keys
const filteredValues = filteredKeys.map(key => yourJSObject[key]);
}

Mapping Array Of Objects By Key

I have two arrays created from a reduce method that searches two existing arrays for dates. It then turns those dates into unique object keys.
The first group is a list of names the second is a set of series of instructions.
The goal is to combine the two arrays that get formed by finding like object keys and adding the matching list object and insert it into the set of instructions with the object key list.
For one it makes an array that looks like :
const listObj = [
{11/20/2020: [{name:'Joe', date:11/20/2020}]},
{11/26/2020 : [{name:'John', date:11/26/2020}]}
]
And this:
const scheduleObj = [
{11/20/2020: {type:'Federal', date:11/20/2020}},
{11/26/2020 : {type:'State', date:11/26/2020}}
]
The final product that i need would look something like:
const scheduleObj = [
{11/26/2020 : {
type: 'State',
list: [{name:'John', date:11/26/2020}]
},
...
]
Where the list is an added key and the array is the array that is associated with the object key
I have used a messy what looks like lodash method to get this to work, but I figure there has to be some sort of mapping I can do.
Any Help Would Be Appreciated
This can be little messy and not failure proof depending on what you have in your listObj or scheduleObj. E.g. repeated date in scheduleObj can lead to a problem using this method, you may have to use another key if the dates are no unique in both lists.
scheduleObj.map((s) => {
// get the first key of the object as the date you're going to group with
const date = Object.keys(s)[0];
// filter the object that matches the date
const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);
// get the list for the given date (or empty array if nothing found)
const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];
// build the result object
return {
[date]: {
type: s[date]['type'],
list: listForDate
}
};
})
Note that I'm always considering you have only one key in the objects inside the lists in listObj or scheduleObj.

How to get the value from a filtered json Array

So I am workin on react and I filtered a json array, but now I just want a value from that filtered json array.
Let me explain, I have this on my json Array
{
name:"name1"
location:"location1"
job:"job1"
},
{
name:"name2"
location:"location2"
job:"job2"
},
I filtered
var filtered = datas.filter(data => data.location == "location1")
and now in console.log(filtered) it will show the array.
But now I just want the
"name" be shown on a string. How can I do that?
Index would be helpful.
console.log(filtered);
console.log(filtered[0].name);
This is another approach apart from the other's answers, using filter, map and then join.
datas.filter(data => data.location === "location1").map(d => d.name).join('')

Getting object from array of objects matching values inside and array of dates with lodash

i have an array of obejcts that has this structure
let events = [ {
"initDate": "2019-11-20",
"finalDate": "2019-11-22",
"intermediateDates": [
"2019-11-20",
"2019-11-21"
],
"priority": 1
},....]
So, i'm trying to get the object that matches from a given array of dates for example :
let filteredDays = [
"2019-11-20",
"2019-11-21",
"2019-11-22"
]
i'm trying with lodash like this:
let eventsFound= [];
let intersection = _.map( this.events,function(value){
let inter = _.intersection(value.intermediateDates,filteredDates);
console.log(inter);
if(inter != []){
foundEvents.push(value);
return value;
}else{
return false;
}
});
when i console log inter i get the first array with values then the next arrays are empty but it keeps pushing all the events into the foundEvents Array and the returned array is the same as the events array.
You're comparing two arrays using !=. In javascript [] != [] is always true. To check if an array is empty, use length property like arr.length == 0.
Use filter instead of using map like a forEach.
To check existance use some/includes combo instead of looking for intersections.
So, filter events that some of its intermediateDates are included in filteredDates:
let eventsFound = _.filter(this.events, event =>
_.some(event.intermediateDates, date =>
_.includes(filteredDates, date)
)
);
The same using native functions:
let eventsFound = this.events.filter(event =>
event.intermediateDates.some(date =>
filteredDates.includes(date)
)
);

Find index of object in javascript using its property name

I want to find Index of javascript array of objects using objects property name. My code is :-
const checkbox = [{'mumbai': true},{'bangalore': true},{'chennai': true},{'kolkata': true}];
How can i find index of chennai? Can i acheive using lodash?
You can use .findIndex()
const checkbox = [
{'mumbai': true},
{'bangalore': true},
{'chennai': true},
{'kolkata': true}
];
const finder = (arr, key) => arr.findIndex(o => key in o);
console.log(finder(checkbox, 'chennai'));
console.log(finder(checkbox, 'kolkata'));
console.log(finder(checkbox, 'delhi'));
checkbox.map((v,i) => Object.keys(v).indexOf("chennai") !== -1 ? i : -1).filter(v => v !== -1)[0]
Will give you the index of "chennai", replace it with any other key to get a different index.
What this does is:
Map the array to an array indicating only indices which contain objects with the wanted key
Filter only the indices which you want
Get the first one (you can use the rest as well if there are multiple entries matching your search)
This works in every browser since it only uses .map() , Object.keys() and .filter()

Categories

Resources