Convert Array to object with custom keys in JavaScript - javascript

I have array which I want to convert to object . Like ['jonas','0302323','jonas84#gmail.com]. Now what I want to achieve I want to convert array into object and I want to assign custom keys into that object .
Expected Result : {name:'Jonas',phone:84394934,email:jonas84#gmail.com}. I am beginner to JS could somone please help me

Destructuring makes this easy:
const yourArray = ['Jimbo', '555-555-5555', 'jimbo#aol.com'];
const [name, phone, email] = yourArray;
const yourObject = { name, phone, email };
console.log(yourObject);
The first statement pulls items out of the array and assigns them to variables. The second statement creates a new Object with properties matching those variable names + values.
If you wanted to convert an Array of Arrays, simply use the same technique with map:
const peopleArrays = [
['Jimbo', '555-555-5555', 'jimbo#aol.com'],
['Lakshmi', '123-456-7890', 'lakshmi#compuserve.com']
];
const peopleObjects = peopleArrays
.map(([name, phone, email]) => ({ name, phone, email }));
console.log(peopleObjects);

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.

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

Appending key value pairs to an array in Javascript

I need an array of key value pairs. How do I append key value in an array inside a for loop.
array_of_countries = {};
country_data.features.forEach(each_country => {
array_of_countries.id = each_country.id;
array_of_countries.country_name = each_country.properties.name;
});
console.log("array of countries", array_of_countries)
This code only gives the last country id and name. I would like to know how to append values in this case. I get the answer as "push" but I am not sure how to use "push" for inserting a key and value. Please help !
{} is an object, not an array. An array is created by []. What you want to do is done using map
const countryData = {features: [{id: 1, properties: {name: 'Foo'}}, {id: 2, properties: {name: 'Bar'}}]};
const countries = countryData.features.map(({id, properties}) => ({id, name: properties.name}));
console.log(countries);
You do need Array.prototype.push for this. Also as you asked for a key-value pair, I assume you want the id to be the key and the properties.name to be the value.
let arrayOfCountries = [];
countryData.features.forEach(country => {
arrayOfCountries.push({
[country.id]: country.properties.name;
});
console.log(arrayOfCountries);

How to avoid "Arrow function expect to return a value" error in Airbnb ESLint

I am running eslint and it is recommended to return a value whenever an arrow function(lambda function) is used. Well that makes sense. However, I come across a case that is hard to walk around.
Dict = {}
Instances = [/* an array of items where items is a dictionary that contains data */]
Instances.map((item) => {
Dict[item.name] = item.url;
});
My goal is to get the data from the Instances array and fill the dictionary Dict with it. I am using the array function to assign key value pair to the dictionary, but that violates the rule of the arrow function.
Is there any iteratools or functions other than map that would help me to achieve the goal, and avoid the rule violation?
Edit: This does not adhere to Airbnb's ES6 Style Guide.
My goal is to get the data from the Instances array and fill the dictionary with it.
Use .reduce
.. and just pass an empty object as the accumulator, filling it up as you iterate through your array.
const instances = [
{ name: 'foo', url: 'https://google.com' },
{ name: 'bar', url: 'https://stackoverflow.com' }
]
const result = instances.reduce((dict, item) => {
dict[item.name] = item.url
return dict
}, {})
console.log(result)
Why not .map?
Array.map always returns a new Array and is meant for mapping each array element to another format.
If your resulting data structure shouldn't be an Array, with the same length as the Array you are operating on, you should avoid using it.
Why .reduce instead of .forEach?
I use forEach only for doing "work" rather than transforming data. Transforming data is almost always achievable with just map and/or reduce.
Here's what I mean by "work":
const users = [userInstance, userInstance, userInstance]
users.forEach(user => user.sendEmail('Hello World'))
Use forEach instead of map.
The point of map is to modify each item in an array and put the modified versions in a new array.
forEach just runs a function on each item.
If you are looking for ES6 solution to fill dictionary object this could help and should pass ESLint also:-
const dict = Instances.reduce((map, obj) => (map[obj.name] = obj.url, map), {});
update
const dict = Instances.reduce((map, obj) => {
let mapClone = {};
mapClone = Object.assign({}, map);
mapClone[obj.name] = obj.url;
return mapClone;
}, {});

Categories

Resources