Assign same key to values gotten from dynamic Array - javascript

I have an array received from backend: ["Drake","Ola","d"], now I need to assign all these values the same key which is id so it looks something like this:
[{id: "Drake"}, {id: "Ola"}, {id: "d"}]
I need a function to do this as the data is gotten after the page has loaded and I have tried many techniques including for loops.
I can also use JQuery if necessary, whats the solution please?

You could use Array#map and generate single objects with the wanted content.
The map() method creates a new array with the results of calling a provided function on every element in this array.
var data = ["Drake","Ola","d"],
result = data.map(function (a) { return { id: a }; });
console.log(result);
ES6
var data = ["Drake","Ola","d"],
result = data.map(a => ({ id: a }));
console.log(result);

Map should do the trick. Just create an object for each value with the id property being that value.
var array = ["Drake","Ola","d"];
var newArray = array.map(function(value){
return {id: value}
})
console.log(newArray);

Related

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;
}, {});

Using the reduce function to return an array

Why is it that when I want to use the push function inside the reduce function to return a new array I get an error. However, when I use the concat method inside the reduce function, it returns a new array with no problem.
All I'm trying to do is pass an array to the reduce function and return the same array.
var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return pV.push(cV);
},[]);
This returns an error. But when I use concat:
var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return pV.concat(cV);
},[]);
It returns the same array.
Any ideas why?
push returns the new length of the array.
What you need is the initially provided array.
So change the code as below.
var store = [0, 1, 2, 3, 4];
var stored = store.reduce(function(pV, cV, cI){
console.log("pv: ", pV);
pV.push(cV);
return pV; // ********* Important ******
}, []);
concat returns the new array combining the elements of the provided array and concatenated elements. so it works.
Just for completeness, and for the next person who happens on this question, what you're doing is typically achieved with map which, as stated in the docs
map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results
Contrast that with the description of reduce:
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
(Emphasis mine) So you see, although you can manipulate reduce to return a new array, it's general usage is to reduce an array to a single value.
So for your code this would be:
var store = [0,1,2,3,4];
var stored = store.map(function(pV){
console.log("pv: ", pV);
return pV;
});
Much simpler than trying to reconstruct a new array using either push or concat within a reduce function.
I know this is the same answer, but I just want to show that using reduce (), the syntax can also be reduced to a single line of code using ES6:
var store = [0,1,2,3,4];
var stored = store.reduce((pV,cV) => [...pV, cV], []);
console.log(stored);
reduce() can be useful if you need to return an array with multiple items for each item iterated:
var inputs = media.reduce((passedArray, video) => {
passedArray.push("-i");
passedArray.push(video.filepath);
return passedArray;
}, []);
Here it's being used to build the input array for FFmpeg;
[{ name: "bob", filepath: "1.mp4" }, { name: "sue", filepath: "3.mp4" }]
=> ["-i", "1.mp4", "-i", "2.mp4]
Array.prototype.push method returns the new length of the array.
Array.prototype.concat method inserts new element into array and returns array back so it can be further processed. This is what you need to do with reduce: pass modified array the the next iteration.
You can always use destructuring:
var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return [...pV, cV];
},[]);
console.log(stored);

Check if an object has a key in javascript

I have two arrays of objects, and I want to filter the first one according to whats on the second one. Here's an example:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
So in this case what I want to return is an array with the objects that have id's 23 and 54 of the first array, with all its possible properties (in this case, title).
Could you give me any hint that could help me?
Get a list of the indexes you want to search on using map:
var indexes = ary2.map(function (el) {
return el.id;
});
filter the results based on the list of indexes:
var result = ary1.filter(function (el) {
return indexes.indexOf(el.id) > -1;
});
DEMO
This might help you.
Loop through ary2, building up an array of each id value (let's call this array existingIds).
After that loop, now loop through ary1. For each item in ary1, check to see if the id value exists in the existingIds array that we just built up. If it does, append the current item to a result array.
I could write the code for you, but it will be a better learning experience if you first try this yourself :)
Might as well make use of some functional programming built into javascript.
filteredResults = ary1.filter(function(ele){
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
filter(function) will iterate through each element of an array, passing it through a callback function. From within that callback iff a true is returned, that value is kept. If false, that value is filtered out.
Also map(function) will iterate through each element of an array passing a callback value as well. All values returned from map callback will be injected into the result. So we can take the id from each element in ary2 and return it in the map function.
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
//Filter for the available ID's, store the resulting objects in a new array
filteredResults = ary1.filter(function(ele){
//map creates an array of just ID's
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
//now do whatever you were planning on doing with your results/
var res = document.getElementById("results");
filteredResults.forEach(function(ele){
res.innerHTML+="<li>{id:"+ele.id + ",title:" +ele.title+"}</li>"
})
console.log(filteredResults);
<ul id="results"></ul>
try this:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
var newary=[];
for(x in ary1){
for(y in ary2){
if(ary1[x].id == ary2[y].id){
newary.push(ary1[x]);
}
}
}
console.log(newary);// here newary will be your return newary;

Categories

Resources