Merge two arrays to multiple objects - javascript

I already have an object witch has two arrays:
const services = {
iconAndLink: [
'Icon1',
'Icon2',
'Icon3',
],
name: [
'Name1',
'Name2',
'Name3',
],
};
I looked into Object.assign(), array.reduce(), map etc... and can't seem to find a decent answer here that merges these two.
For final result I need:
services = [
{
icon: 'Icon1',
name: 'Name1'
},
{
icon: 'Icon2',
name: 'Name2'
},
{
icon: 'Icon3',
name: 'Name3'
},
]
Note that I need to have the icon and name keys.
Is this even possible in js?

This should work
const services = {
iconAndLink: ["Icon1", "Icon2", "Icon3"],
name: ["Name1", "Name2", "Name3"],
};
let result = services.iconAndLink.map(function (icon, index) {
return { icon: services.iconAndLink[index], name: services.name[index] };
});
console.log(result);
Make sure both arrays same the same length and both are ordered

A simple forEach loop using index would do the trick
const services = {
iconAndLink: [
'Icon1',
'Icon2',
'Icon3',
],
name: [
'Name1',
'Name2',
'Name3',
],
};
let newarray = [];
services.iconAndLink.forEach((el, index) => newarray.push({
icon: el,
name: services.name[index]
})
);
console.log(newarray)

const services={iconAndLink:["Icon1","Icon2","Icon3"],name:["Name1","Name2","Name3"]};
const res = services.name.map((e, i) => ({
icon: e,
name: services.iconAndLink[i]
}))
console.log(res)

Assuming the arrays are of the same size, you can do:
const services = { iconAndLink: [ 'Icon1', 'Icon2', 'Icon3', ], name: [ 'Name1', 'Name2', 'Name3', ], };
const newArr = [];
for (let i = 0; i < services.iconAndLink.length; i++) {
newArr.push({icon: services.iconAndLink[i], name: services.name[i]})
}
console.log(newArr)

Related

How filter array of objects based on objects exists in another array of objects?

I have
array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];
I want to filter objects of array1 which exists in array2.
So I need to have
[{ name: sample1 }, { name: sample2 }]
How can I get it in javascript?
You can use .filter and .some function in JavaScript ,
Here is the example
const array1 = [{ name: "sample1" }, { name: "sample2" }, {
name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
return array2.some(function(obj2) {
return obj.name== obj2.name;
});
});
console.log(Result)
You can use object destructuring, the map() and .includes() methods as shown below:
const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];
const filtered = array1.filter(
({name}) => array2.map(o => o.name).includes(name)
);
console.log( filtered );

Check if object key exists in array of object and add if not exists

Do you know guys how to do it simplier/smarter ?
I wanna add a label key with name value if the key doesn't exist in object. This is my list:
myList = [
{
name: 'Candy',
label: 'xx',
},
{
name: 'Mike',
label: 'yy',
},
{
name: 'Betty',
}
]
And my solution:
assignLabel = list => {
const casesWithoutLabel = list.filter(({ label }) => !label).map(item => ({
...item,
label: item.name
}))
const casesWithLabel = list.filter(({ label }) => label)
return [ ...casesWithoutLabel, ...casesWithLabel ]
}
assignLabel(myList)
Output
[
{
name: 'Candy',
label: 'xx',
},
{
name: 'Mike',
label: 'yy',
},
{
name: 'Betty',
label: 'Betty'
}
]
It gives me good output, but it's not elegant and I don't have idea how to improve now. Please help me!
I have create simple script for you, please have a look!
let myList = [
{
name: 'Candy',
label: 'xx',
},
{
name: 'Mike',
label: 'yy',
},
{
name: 'Betty',
}
];
let list = myList.map((item) => {
let {name, label} = item;
if(label == undefined){
item["label"] = name;
}
return item;
});
console.log(list);
Your code seems very advanced for only assigning a property, so maybe I am missing something, but you could simply loop through the list (or filter oc)
myList = [{name: 'Candy',label: 'xx',},{name: 'Mike',label: 'yy',},{name: 'Betty',}];
for(const obj of myList)
if(!obj.label)obj.label = obj.name;
console.log(myList);

I have to return filtered object

I have array, which i get from checkbox checking.
And I have array of objects with categrories.
I want to get an array filteredPeople that contains only objects with categories that contains at least one of from selectedClicents
let selectClients = ['Web', 'Design'];
let people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
You can use filter, some and includes
let selectClients = ['Web', 'Design'];
let people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
let final = people.filter(({category})=> selectClients.some(v=>category.includes(v)))
console.log(final)
You can use Array.prototype.some and Set.prototype.has along with filter to get the filtered list from people array
I've used a ES6 Set for O(1) lookup:
const selectClients = ['Web', 'Design'];
const keys = new Set(selectClients);
const people = [
{ category: ['Web', 'Design'] },
{ category: ['Web'] },
{ category: ['PWA', 'Design'] },
{ category: ['Ecommerce'] },
];
const res = people.filter(({category}) => category.some(cat => keys.has(cat)));
console.log(res);

Array.filter() to remove duplicate Ojects

I would like to fuse Array.filter() function to remove duplicate objects
I am able to achieve in the case of string or integer arrays. But I am not able to achieve the same with array of objects as in the second case of names
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let x = names => names.filter((v, i, arr) => arr.indexOf(v) === i);
console.log(x(names)); //[ 'John', 'Paul', 'George', 'Ringo' ]
const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" } ];
// returns the same original array
Could you please help?
Using Array#reduce() and a Map accumulator then spread the values() of the Map into array
const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" } ];
const unique = [... names.reduce((a,c)=>(a.set(c.name,c)),new Map).values()]
console.log(unique)
Use Array.reduce and Object.values
Iterate over the array and create an object with key as name and value as object from array. In case of objects with same name, the value will be overwritten in resultant object. Finally use Object.values to collect all the unique objects.
const names = [{ name: "John" },{ name: "Paul" },{ name: "George" },{ name: "Ringo" },{ name: "John" } ];
let result = Object.values(names.reduce((a,c) => Object.assign(a, {[c.name]:c}),{}));
console.log(result);
For tweaking - Plunker
const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" }
];
/* unique => Filter: Remove all duplicate items from an array. Works with plain objects as well, since we stringify each array item.
* #type public Function
* #name unique
* #return Function( item )
* #notes
*/
const unique = () => {
const seen = {};
return item => {
const json = JSON.stringify( item );
return seen.hasOwnProperty( json )
? false
: ( seen[ json ] = true );
};
};
const result = names.filter( unique() );
console.log( result );
You could use lodash's _uniqBy for this:
const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" } ];
const result = _uniqBy(names, 'name');
This can be done with the help of Sets as well
var names = [{ name: "John" },{ name: "Paul" },{ name: "George" },{ name: "Ringo" },{ name: "John" } ];
var result = Array.from(
names.reduce((s, d) => s.add(d.name), new Set)
, d => ({ name: d })
)
console.log(result)
Keith had a great suggestion to use findIndex with filter instead of indexOf. Object literals are always unique references, so we cannot compare them. We can however compare the name keys between the objects. We can do this with the aforementioned functions.
const names = [
{ name: "John" },
{ name: "Paul" },
{ name: "George" },
{ name: "Ringo" },
{ name: "John" }
];
console.log(names.filter(({name1}, i, a) => {
return i == a.findIndex(({name2}) => {
return name1 == name2;
});
});
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
function removeDups(names) {
let unique = {};
names.forEach(function(i) {
if(!unique[i]) {
unique[i] = true;
}
});
return Object.keys(unique);
}
removeDups(names); //'John', 'Paul', 'George', 'Ringo'

Return duplicate objects and its position in javascript

I have a big set of objects in javascript array. I Need to find all duplicate object having same name.
e.g.
values = [
{ name: 'Name1', index:0 },
{ name: 'Name2', index:1 },
{ name: 'Name1', index:2 },
{ name: 'Name2', index:3 },
{ name: 'Name1', index:4 },
]
What I expect is a array having two objects
values = [
{ name: 'Name1', index:2 },
{ name: 'Name2', index:3 },
{ name: 'Name1', index:4 }
]
because these are the duplicates.
New additions to ES6 are really interesting here, such as the Set class. This code does not modify your initial object, but it's simple to adapt.
function unique(values) {
const knownNames = new Set();
const result = [];
for (const value of values) {
if (!knownNames.has(value.name)) {
knownNames.add(value.name);
result.push(value);
}
}
return result;
}
This probably isn't the most efficient way and you should probably use the Set if you don't need to worry about IE9
values = [
{ name: 'Name1', index:0 },
{ name: 'Name2', index:1 },
{ name: 'Name1', index:2 },
{ name: 'Name2', index:3 },
{ name: 'Name1', index:4 },
]
// check an array for an object with a matching name property
// `some` will return early so you don't need to process the whole array
// if a match is found
const contains = (name, arr) => arr.some(item => item.name === name)
// reduce the array to keep the value contained
const output = values.reduce((acc, value) => {
if (!contains(value.name, acc)) {
return acc.concat(value)
}
return acc
}, [])
console.log('first unique', output)

Categories

Resources