This question already has answers here:
How to compare arrays in JavaScript?
(61 answers)
Closed 12 months ago.
const users = [
{name:'John',age:24},
{name:'Victor',age:28}
];
const newUser = JSON.parse(JSON.stringify(users));
console.log(users);
console.log(newUser);
console.log(typeof(users));
console.log(typeof(newUser));
console.log(users==newUser)
OUTPUT:
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
object
object
false
object users and newUser have exactly same items and values.
They why users==newUser is false?
In Javascript the equals operator compares object instances, not values. They are 2 different instances, so not equal.
One way to compare the values is to use a deep equals library. Another way is to compare the JSON.stringify value.
JSON.stringify(users) === JSON.stringify(newUser) // true
A caveat of the stringify approach is that undefined values are stripped.
Related
This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed last year.
Below is the array with objects:
myArray:[
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]}
I tried this but I am not getting output:
item= myArray.filter(element => element.includes("US"));
I am new to Angular.
let filteredArray = myArray.filter(function (item){
return item.userId.substring(0,2).includes('US')
})
Console.log(filteredArray)
//Output
[ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' },
{ name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
As noted by #halfer - You need to filter on the property that you are interested in - in this case - 'userId' - you can do this by simply adding the property into the code you already had tried and it will log out the specified items - or alternatively - you can make a utility function that takes the array, property and target string as arguments and this will allo2w you to search / filter other arrays and by any property and target string .
These two options are shown below and both log out the same results.
const myArray = [
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]
// option 1 - direct filtering
const matchingItems = myArray.filter(element => element.userId.includes("US"));
console.log(matchingItems);
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
//option 2 - create a function that takes arguments and returns the matches
const matches = (arr, prop, str) => {
return arr.filter(element => element[prop].includes(str));
}
console.log(matches(myArray, 'userId', 'US'));
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
i wanted represent first two letters of phone number,i want to get phone numbers first two characters. what i have tried is below Get first two of attribute and find target based on it.
let object = [
"key": {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}]
what i have tried is below
object[0].substr(0,2);
let test = {
key: {
"login-attempt": 1,
name: "ADMIN",
phone: "0777123456",
}
};
console.log(test.key.phone.substr(0,2));
You're more likely to have an object like this:
let object = {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
};
In this case, your code might be:
let prefix = object.phone.substr(0,2);
Or you might have an array of objects:
let object = [
{
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
},
{
login-attempt: 1
name: "CLERK"
phone: "2222222222"
}
];
You can get the 1st two characters of the second element like this:
let prefix = object[1].phone.substr(0,2);
If the element was nested within "key":
let object = {
key: {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}
};
let prefix = object.key.phone.substr(0,2);
And so on...
This question already has answers here:
javascript filter array of objects
(8 answers)
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 1 year ago.
Suppose there is an Array that has some objects like below
[{name:"Bruce wayne" age:42 DOA:true},{name: "Dick grayson" age:28 DOA:true},{name:"Jason todd" age:24 DOA:false}]
and I want to get a new Array with Objects which DOA is true (bruce and dick).
Is there any good API or something to do this?
your help is going to be appreciated Thx!
You can simply use Array.prototype.filter:
const data = [{
name: "Bruce wayne",
age: 42,
DOA: true
}, {
name: "Dick grayson",
age: 28,
DOA: true
}, {
name: "Jason todd",
age: 24,
DOA: false
}];
console.log(data.filter(obj => obj.DOA));
Mind that your JSON was also invalid.
This question already has answers here:
Shortest way to find duplicates in array of arrays of objects by property
(1 answer)
Find duplicate object by property and Merge using Javascript or UnderscoreJS
(1 answer)
Closed 2 years ago.
I need to check if an array contains duplicated values.
Lets say I have the following array of arrays:
array = [
{ id: 123, name: 'Emily', address: 'UK' },
{ id: 123, name: 'Ross', address: 'USA' },
{ id: 157, name: 'Joey', address: 'Italy' },
];
As you can see, I have 2 arrays, aving the same ID id=123, and I need to detect these 2 rows, so we can clean the data we have.
P.S. I am only interested in checking duplication on IDs and Names at the same time.
I did the following logic, but it doesn't make sense, as it returns rows more than the existed ones:
ngOnInit() {
this.array.forEach((row) => {
this.array.find(element => {
if (element['id'] === row['id']) {
console.log(row)
}
})
})
}
The output is like:
123 Emily
123 Emily
123 Ross
123 Ross
157 Joey
My needed out output is as the following:
123 Emily
123 Ross
Here is a stackblitz.
You can use filter and map like this to get a distinct-like behaviour:
function distinct(myArray, prop) {
return myArray.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
});
}
This question already has answers here:
Find by key deep in a nested array
(21 answers)
Closed 5 years ago.
I have and multidimensional object that looks like this:
obj = {
'someString': {
name: 'John',
page: 'some url',
number: 4
},
'someString2': {
name: 'Bill',
page: 'some url',
number: 7
}
}
How do I find the first level key (in this case "someString2") where "number" is equal to 7?
The number is always unique and is the only thing I know beforehand.
Here you go. Using Array.find function to look for the appropriate key.
const numberToLookFor = 7;
const data = {
someString: {
name: 'John',
page: 'some url',
number: 4,
},
someString2: {
name: 'Bill',
page: 'some url',
number: 7,
},
};
const myKey = Object.keys(data).find(x => data[x].number === numberToLookFor);
console.log(myKey);