Mapping Array Of Objects By Key - javascript

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.

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]);
}

Retrieve all matching values from json array

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

looking to remove duplicates from an array with key value pair

I have duplicate values looks like as shown in below figure
I have used below code but its only giving the names like as ashare1 guideline2and i am looking for id as well.
please find the below code currently i have used
const optionMap0 = [
...new Set(libraryEquipment.map(e => e.equipmentSource.name)),
{
id: '1d037be564c548eebe71db4e45e26cf7',
name: 'None',
},
];
Could any one please suggest any idea on how to get distinct values from the above array of objects.
many thanks in advance
You can convert it to an object, with the key as the name, and the value as the object itself, and then use Object.values() to get the objects.
const obj = {};
libraryEquipment.forEach(e => obj[e.equipmentSource.name] = e.equipmentSource);
const optionMap0 = Object.values(obj);
Unlike set, if you have more than one object with the same name, it will keep the last one. You can check before adding the object so it will use the first object with the same name, like so:
const obj = {};
libraryEquipment.forEach(e => {
if (!obj[e.equipmentSource.name])
obj[e.equipmentSource.name] = e.equipmentSource'
});
const optionMap0 = Object.values(obj);

JavaScript loop, create object, but shows zero in length

I have a javascript method, where I'm trying to group my data by 'date', which works fine.
But when I look at the length of my object it shows, 'zero'.
Is there a better way to do this? and keep the length of the new variable?
groupByDate(snapshot) {
let list = []
this.orders.reduce(function (a, c) {
if(!list[c.date]) {
list[c.date] = [];
}
list[c.date].push(c);
});
this.ordersByDate = list
console.log(list)
}
You are pushing properties into an array. You are not setting the indexes of the array. So you should be using an object and not an array. Your use of reduce is also not correct. You are treating it like a forEach loop.
So use an object and use reduce the way it is supposed to be
let list = this.orders.reduce(function (o, c) {
o[c.date] = o[c.date] || []
o[c.date].push(c)
return o
}, {})
console.log(Object.keys(list).length)
I would use a dictionary (key, values) for that:
list {
date1: [obj1-1, obj1-2, ...],
date2: [obj2-1, obj2-2, ...],
...
}
list = {};
this.orders.forEach(order => {
if (!list.hasOwnProperty(order.date)) {
// If it is the first time we meet this date, create an array with th first element
list[order.date] = [order];
} else {
// We have already meet the date, thus the key exists and so do the array. Add element to array
list[order.date].push(order);
}
});
It seems you have an array and its indexes are the dates. I assume the dates are big numbers (date from 1970 in milliseconds, something like that), which may lead to having a very very big array 99,9% empty. That is why according to me you should use an object and not an array.
Or maybe those are not dates but id's of dates ?

How do I add key:value pair in an order in javascript

I need to add key:value into an object.
var a = {}
a['first'] = [a,bunch,of,stuff]
a['eight'] = [another,bunch,of,stuff]
a['two'] = [more,stuff]
but now variable 'a' contains
{eight: [a,bunch,of,stuff],first: [another,bunch,of,stuff],two: [more,stuff]}
while what I wanted was
{first: [another,bunch,of,stuff], eight: [a,bunch,of,stuff],two:[more,stuff]}
I'm guessing the order is based on the alphabetical order of the keys. This is a problem, because I want to display the data into hbs using {#each model as |key value|} in the same order as I wanted it.
in most languages lists have order where objects and sets do not. objects are key value and have no order.
in js arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays
this basically means you can place data anywhere in array, and it will be in order in the array
var idx = [];
idx[0] = 'hello';
idx[999] = 'world';
so what i believe you're looking for is
var listOfThings = [];
listOfThings.push({ 'first': [ 'things' ] })
listOfThings.push({ 'eight': [ 'stuff' ] })
listOfThings.push({ 'two': [ 'more'. 'things' ] })
then you can loop over accessing the key and value for each object.
Example you have an object, which is already have 2 key pairs, a1 & b2. Then you would like to add k3, you can use this method :
let objData = [{"a1":10,"b2":20},{"b2":11,"a1":23}]
Object.keys(objData).map(
function (object) {
// add k3
objData[object]["k3"] = "foo"
})
Then if you want to sort the keys alphabetically, use this method :
function orderKeyAlfAsc(obj) {
let data = []
for (var i in obj)
data.push(Object.keys(obj[i]).sort().reduce((r, k) => (r[k] = obj[i][k], r), {}))
return data
}
let orderedData = orderKeyAlfAsc(objData)

Categories

Resources