This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 7 years ago.
I am trying to determine if a key name is present in my array of object. As an example, how would I verify if the key with a name of 'name' equals the argument passed in my function call? Below is code to further clarify.
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var test = function(arr, propName){
var result = [];
for(var i = 0; i < arr.length; i++){
if(arr[i][propName] === propName){
result.push(arr[i][propName]);
}
}
return result;
}
func(stooges, "name");
Using underscore.js:
var names = _.pluck(stooges, 'name');
In fact this is the very example given on their page?!
So, on the basis that you knew this, but want to know how to write something similar:
function pluck(array, prop]) {
return array.map(function(entry) {
return entry[prop];
});
}
or more safely, returning an empty array if the initial array is undefined:
function pluck(array, prop]) {
return array ? array.map(function(entry) {
return entry[prop];
}) : [];
}
Related
This question already has answers here:
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How to determine if Javascript array contains an object with an attribute that equals a given value?
(27 answers)
Closed 2 years ago.
I have this code:
const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
console.log(arr.includes({name:"Bill", age:11}))
Here i want to check if the array includes {name:"Bill", age:11}.
Why i get false? And how to make this checking using includes?
The includes() method compares objects by reference and not by value. In your case the three objects have three different references although they have the same properties and the same values in them.
const bill = { name: 'Bill', age: 11 }
const arr = [bill, { name: 'Jane', age: 18 }]
arr.includes(bill) // true (same reference)
arr.includes({ name: 'Bill', age: 11 }) // false (different reference)
If you want to find objects by value, you can use the find() method and pass a filter function which checks if each property of the object matches your criteria.
const arr = [{name:"Bill", age:11}, {name:"Jane", age:18}]
const exists = Boolean(arr.find(x => x.name === 'Bill' && x.age === 11))
// or even simpler using the `some()` method
const exists = arr.some(x => x.name === 'Bill' && x.age === 11)
You can create a custom array prototype method for this like includesObj
const arr = [
{name:"Bill", age:11},
{name:"Bill", age:11}
]
Array.prototype.includesObj = function(obj) {
for(let i = 0; i < this.length; i++) {
if(JSON.stringify(this[i], Object.keys(this[i]).sort()) === JSON.stringify(obj, Object.keys(obj).sort())) return true;
}
return false;
}
console.log(arr.includesObj({name: "Bill", age: 11}))
console.log(arr.includesObj({age: 11, name: "Bill"}))
console.log(arr.includesObj({name: "Bob", age: 11}))
This question already has an answer here:
Index an array of arrays with an array of indexes in javascript
(1 answer)
Closed 2 years ago.
If I have an array describing the path to an object property, e.g ['user', 'personal_info', 'age] and I want to set an object's property according to it, say myObject.user.personal_info.age = 30, how would I do that?
Loop through the keys in the array and use them to access the object properties as though it were a dictionary. (Skip the last key because you need it to access the final property.)
function updatePersonAge(person) {
let keys = ['user', 'personal_info', 'age'];
let obj = person;
for (let i = 0; i < keys.length - 1; i++) {
obj = obj[keys[i]]; // user, personal_info
}
obj[keys[keys.length - 1]] = 30; // age
}
let person = { user: { personal_info: { age: 10 }}};
updatePersonAge(person);
console.log(person);
This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 5 years ago.
I am having trouble with some basic javascript. I want this function to return an array of all objects within the given array that have the name "Ray" assigned to name. I can't get the push part to work.
const people = [{name: "Jack", age: 30}, {name: "Ray", age: 32}, {name: "Anna", age: 28}];
function findRay(arr) {
let response = [];
for(let i = 0; i < arr.length; i++) {
if(arr[i].name === "Ray") {
response.push(arr[i]);
}
}
return response;
}
console.log(findRay(people));
While not exactly what you were looking for, this is a good use case for filter(). So you could do something like const findRay = arr => arr.filter(person => person.name === "Ray").
This question already has answers here:
Alter and Assign Object Without Side Effects
(7 answers)
Closed 6 years ago.
I know how to remove an item from a json array, but I can't seem to make it work when adding.
The array:
var users = [
{name: 'james', id: '1'}
]
Want to add so it becomes:
var users = [
{name: 'james', id: '1'},
{name: 'thomas', id: '2'}
]
Here's the code for removing an array:
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
removeValue('name', value);
//space removed
What changes would I need to make to reverse to add values to the array?
With Array.prototype.push() ?
var sports = ["plongée", "baseball"];
var total = sports.push("football", "tennis");
console.log(sports); // ["plongée", "baseball", "football", "tennis"]
console.log(total); // 4
I think a more fitting function is filter than map.
Array.prototype.removeValue = function(name, value){
var array = $.filter(this, function(v,i){
return v[name] !== value;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
I am only assuming the length and push hacks work, since I've never used them myself.
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
An object with an array of objects, and a function that returns all the names of each object in the array. This works.
var persArr = {friends:[
{name: "Adam", age: 37},
{name: "Ben", age: 36},
{name: "Chris", age: 46}],
getFriend:function(){
return this.friends.map(function(friend){
return friend.name;
}).join(', ').slice();
}};
var names = persArr.getFriend();
console.log(names);
How can I return a name and age property of an object, based on search criteria?
example: {name:"Chris", age:46},
{name:"Ben",age: "36"}
perArr.getFriend("Chris");
Just change your return function to return an object. Something like:
getFriend:function(name){
return this.friends.filter(function(friend){
if(friend.name===name){
return {name:friend.name, age:friend.age};}
});
}};
var nameAge = persArr.getFriend('Adam');
console.log(nameAge);
Could change your function to use filter() instead of map:
getFriend:function(name){
var match = this.friends.filter(function(friend){
return friend.name === name;
});
return match.length ? match[0] : false;
}};
You can iterate over the list and check if the name matches your search parameter.
If it matches return the actual object.
In case it doesn't find anything return undefined.
getFriend: function(name) {
for (var i = 0; i < friends.length; i++) {
if (friends[i].name == name) {
return friends[i];
}
}
return undefined;
}