How to assert that all objects inside array do not include multiple properties.
Example all of them should not include keys "email" and "phone".
const myArray = [
{name: "John Doe", email: "john#gmail.com", phone: "9xxxxxxxxxx"},
{name: "Jane Doe", email: "jane#gmail.com", phone: "9xxxxxxxxxx"},
{name: "Johny Doe"}
]
// this seems to do what I want
// but doesn't "something" check if any object passes the test?
expect(myArray).to.contain.something.that.does.not.include.any.keys("email", "phone")
Using chai-things.
You can filter your array for elements having both keys set:
myArray.filter(a => a.email && a.phone)
and expect the count is 0:
expect(myArray.filter(a => a.email && a.phone)).to.be.an('array').that.is.empty;
Related
I have array of objects like this:
var array = [
{
name: "John",
surname: "Doe",
title: "mister"
},
{
name: "Jane",
surname: "Smith",
title: "miss"
},
{
name: "Doe",
surname: "Mustermann",
title: "mister"
}
]
I want to implement a search term through this that will look through multiple properties while sorting them with property priority.
Example: If search term would be Doe, I would like to get this output:
[
{
name: "Doe",
surname: "Mustermann",
title: "mister"
},
{
name: "John",
surname: "Doe",
title: "mister"
}
]
name property has higher priority than surname, that's why hit on name object would go on top.
Filter function only filters through array, but I also would need to move objects up based if search term hit specific field that has higher priority.
I tried implementing this with combination of filter and sort, but unfortunately this was a failure due to both searching through multiple fields in objects, with moving some objects on top depending on which property search was found.
Have a list of fields, ordered by priority:
let fields = ['name', 'surname', 'title']
and then compute the result like this:
let result = fields.flatMap(f => array.filter(x => x[f] === search))
I have a object which has some properties for one user, and I have array of objects which is returned from API.
My goal is to check which object of Array of objects has the same property as the one single initial object, and then it should return only part of it's properities.
I have tried to use .map on Array of objects but it seems not workig.
Below is the code example. I have also prepared codesandbox if You wish.
const user =
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
car: "audi"
}
;
const usersAnimal = [
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
animal: "cat",
animalSize: "small",
animalName: "Bat"
},
{
name: "john",
lastName: "smith",
fullName: "john smith",
animal: "dog",
animalSize: "middle",
animalName: "Jerry"
},
{
name: "Anna",
lastName: "Nilsson",
fullName: "Anna Nilsson",
animal: "cow",
animalSize: "big",
animalName: "Dorrie"
}
];
const filtered = usersAnimal.map((userAnimal)=>userAnimal.fullName === user.fullName && return userAnimal.animalName & userAnimal.animalSize & userAnimal.animal);
thanks
https://codesandbox.io/s/admiring-edison-qxff42?file=/src/App.js
For case like this, it would be far easier if you filter it out first then proceed using map:
const filtered = usersAnimal
.filter((animal) => animal.fullName === user.fullName)
.map(({ animalName, animalSize, animal }) => {
return {
animalName,
animalSize,
animal
};
});
I am providing a for loop solution as I haven't learnt many array methods in javascript.
For me the simplest option is to use a for loop and an if check to loop through the arrays values to check for included values.
for (let v in usersAnimal) {
if (usersAnimal[v].fullName === user.fullName) {
console.log(usersAnimal[v])
}
}
The code above will log the entire usersAnimal object containing the fullname we are looking for.
{
name: 'jan',
lastName: 'kowalski',
fullName: 'jan kowalski',
animal: 'cat',
animalSize: 'small',
animalName: 'Bat'
}
commented for further understanding
for (let v in usersAnimal) {
//loops though the array
if (usersAnimal[v].fullName === user.fullName) {
//when the index value 'v' has a fullname that matches the user fullname value
// it passes the if check and logs that object value
return console.log(usersAnimal[v])
//return true...
}
//return null
}
//etc
If you want to filter, I recommend you to use filter.
The map method will create a new array, the content of which is the set of results returned by each element of the original array after the callback function is operated
const user = {name:"jan",lastName:"kowalski",fullName:"jan kowalski",car:"audi"};
const usersAnimal = [{name:"jan",lastName:"kowalski",fullName:"jan kowalski",animal:"cat",animalSize:"small",animalName:"Bat"},{name:"john",lastName:"smith",fullName:"john smith",animal:"dog",animalSize:"middle",animalName:"Jerry"}];
// Get an array of matching objects
let filtered =
usersAnimal.filter(o => o.fullName === user.fullName);
// You get the filtered array, then you can get the required properties
filtered.forEach(o => {
console.log(
'animal:%s, animalSize:%s, animalName:%s',
o?.animal, o?.animalSize, o?.animalName
);
});
// Then use map to process each element
filtered = filtered.map(o => {
const {animal, animalSize, animalName} = o;
return {animal, animalSize, animalName};
});
console.log('filtered', filtered);
I would like to combine elements of 2 arrays based on the name. For example:
Array1 = [
{name: "name1", language: "lang1"},
{name: "name2", language: "lang2"},
{name: "name3", language: "lang3"}]
Array2 = [
{name: "name1", subject: "sub1"},
{name: "name2", subject: "sub2"},
{name: "name3", subject: "sub3"}]
I need to generate the following array:
Array3 = [
{language: "lang1", subject: "sub1"},
{language: "lang2", subject: "sub2"},
{language: "lang3", subject: "sub3"}]
The logic I could think of was to write an explicit for loop to compare every element of first array with every element of second array and check if name matches as shown below.
let Array3 = []
for(let i=0;i<Array1.length;i++)
{
let elem = Array1[i];
for(let j=0;j<Array2.length;j++)
{
if(Array2[j].name===elem.name)
{
Array3.append({language: elem.language, subject: Array2[j].subject})
break;
}
}
}
However, my actual dataset is quite large and this seems inefficient. How can this can be achieved in a more efficient manner (like using higher order functions or something)?
Using a Map for O(1) lookup of one of the arrays using name as key lets you iterate each array only once.
const Array1=[{name:"name1",language:"lang1"},{name:"name2",language:"lang2"},{name:"name3",language:"lang3"}],Array2=[{name:"name1",subject:"sub1"},{name:"name2",subject:"sub2"},{name:"name3",subject:"sub3"}];
const a1Map = new Map(Array1.map(({name, ...r})=> [name, {...r}]));
const res = Array2.map(({name, ...r}) => ({...r, ...a1Map.get(name)}))
console.log(res)
You need to iterate over the two arrays and group the generated object in a map having the name as the key:
let Array1 = [
{name: "name1", language: "lang1"},
{name: "name2", language: "lang2"},
{name: "name3", language: "lang3"}
];
let Array2 = [
{name: "name1", subject: "sub1"},
{name: "name2", subject: "sub2"},
{name: "name3", subject: "sub3"}
];
let map = new Map();
Array1.forEach(e => map.set(e.name, {language: e.language}));
Array2.forEach(e => {
if(map.has(e.name))
map.set(e.name, {...map.get(e.name), subject: e.subject});
});
let Array3 = [...map.values()].filter(e => e.language && e.subject);
console.log(Array3);
Yes you are thinking in right order , you need to use the sort algorithm logics , I will say nested for loops will be just as good. With larger dataset , since you need to extract the values from two different array you can use the nested for loops.
for(int i=0;i>array1.length();i++){
This can be use for first array
Define String x=",";
For second
for(int j=0;j>array2.length();j++)
{
Check if ( (","+j+",").contains(x)) then break;
If array1 name found in array 2, store array3 as you want
Also Store value of j in x
Like x=x +j+",";
}}
This way your nested for loop will skip the comparison code.
Above algo is raw but will reduce the complexity a significant bit.
I found unexpected result when try to merge with lodash object with flat array inside.
Here the example:
var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };
const person = { age: '31', values: ["PT"] };
var people2 = { name: 'Andrew', age: '30', values: [{ pippo : 1}] };
const person2 = { age: '31', values: [{ pippo : 2}] };
// Now merge person back into people array
console.log(_.merge({}, people, person));
console.log(_.merge({}, people2, person2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
The result of first console.log is
{
age: "31",
name: "Andrew",
values: ["PT", "PORTA 31"]
}
And not as expected
{
age: "31",
name: "Andrew",
values: ["PT"]
}
Someone can explain me why and give me a solution to make sure that with a flat array it takes me the correct value
I think assign is better in this case than merge
This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };
const person = { age: '31', values: ["PT"] };
console.log(_.assign({}, people, person));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
I believe _.assign(people, person) would produce the desired outcome in this case https://lodash.com/docs/4.17.15#assign
This functionality is also native and can be used like this Object.assign(target, source)
I'm still learning javascript patterns, and I'm curious about this one.
If I have an array of objects, should I make the array of objects not have keys (Example A), or use their keys (Example B)?
An array of objects without any key:
var soylent_green_candidates = [{
id: 12341,
name: "Don",
gender: "Male",
weapon_of_choice: "Kangaroo Cannon"
},
{
id: 24325,
name: "Jimmy",
gender: "Male",
weapon_of_choice: "Sushi Blaster"
},
...
]
Or an array of objects using the unique ID's as keys:
var soylent_green_candidates = [
12341: {
name: "Don",
gender: "Male",
weapon_of_choice: "Kangaroo Cannon"
},
24325: {
name: "Jimmy",
gender: "Male",
weapon_of_choice: "Sushi Blaster"
},
...
]
Your second example is invalid, so that should put the question to sleep.
In Javascript you have the option of arrays, which are sorted but essentially "key less". Each array entry can only be accessed by its numeric index, period.
The other option is objects, which have no guaranteed order but are keyed by arbitrary values.
['foo', 'bar', 'baz']
{ foo : 'bar', baz : 42 }
You make the choice based on these two criteria, order and requirement for keys.
(Note: while you can use arbitrary numeric indices for arrays, you can't do so using the literal syntax [..], and it's not usually a good idea. If you need explicit keys, you want objects.)