Javascript Update object of array by attribute of the object - javascript

I have an array of person objects and I want to update one of object in place.
persons: [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 13
}, {
id: '3',
name: 'David',
age: 14
}]
The function I have is:
function updatePersonsWith(id, propName, value) {
this.persons.???
}
The arguments passed are id of the person I want to update, propName is the properties of person object, can be id, name or age, value is the value I want to replace with.
I want to find an object by it's id and update only this object of the array.
updatePersonsWith(2, age, 16)
The result would be:
persons: [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 16
}, {
id: '3',
name: 'David',
age: 14
}]
Could be ES6 or using lodash.

Try:
let person = this.persons.find((person) => {
return person.id === id;
});
if (person && person[propName]) {
person[propName] = value;
}
Working example:
var persons = [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 13
}, {
id: '3',
name: 'David',
age: 14
}];
function update(id, prop, val) {
var person = persons.find(function(p) {
return p.id === id;
});
if (person && person[prop]) {
person[prop] = val;
}
}
update('1', 'age', 77);
console.log(persons[0].age);

You can use this:
let persons = [{
id: '1',
name: 'John',
age: 12
}, {
id: '2',
name: 'Tom',
age: 13
}, {
id: '3',
name: 'David',
age: 14
}];
function updatePersonsWith(id, propName, value) {
let item = persons.find((v) => {
return v.id == id;
});
if (item && item.hasOwnProperty(propName)) {
item[propName] = value;
}
};
updatePersonsWith(2, 'age', 16);
console.log(persons)

Using lodash, you can do like,
function updatePersonsWith(id, propName, value) {
var match = _.find(persons , function(person) { return person.id === id });
if(match)
match[propName] = value;
}

Related

Replace the records of particular category

There is one scenario where i need to replace the existing records from cached data with new incoming data source. Looking for the cleaner approach to handle the array operations.
For example:
var userCategory = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'bar',
},
{
id: 'platinum',
name: 'foo',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
Here is new users of particular category
var newPlatinumUsers = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
];
This is the expected result needed:
var expected = [
{
id: 'platinum',
name: 'bob',
},
{
id: 'platinum',
name: 'mike',
},
{
id: 'gold',
name: 'tom',
},
{
id: 'silver',
name: 'billy',
},
];
I tried with filtering all the platinum user from existing records then added the new records but it looks verbose
Is there any cleaner approach like lodash operator??
Thanks for your time!!!
May you are looking for this.
function getUnique(arr){
// removing duplicate
let uniqueArr = [...new Set(arr)];
document.write(uniqueArr);
}
const array = ['acer','HP','Apple','Apple','something'];
// calling the function
getUnique(array);
Verify my answer if it help you.
Please find the Javascript implementation of the same
var userCategory = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'bar', },
{ id: 'platinum', name: 'foo', },
{ id: 'gold', name: 'tom', },
{ id: 'silver', name: 'billy', },
];
var newPlatinumUsers = [
{ id: 'platinum', name: 'bob', },
{ id: 'platinum', name: 'mike', },
];
const result = [...newPlatinumUsers];
userCategory.forEach((node) => {
if(node.id !== 'platinum') {
result.push(node);
}
});
console.log(result);
With this solution you can change more than one category:
var userCategory = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'bar'},
{id: 'platinum',name: 'foo'},
{id: 'gold',name: 'tom'},
{id: 'silver',name: 'billy'},
];
var newUsers = [
{id: 'platinum',name: 'bob'},
{id: 'platinum',name: 'mike'},
{id: 'gold',name: 'will'},
{id: 'gold',name: 'jerry'},
];
const idsToReplace = {}
const result = [...newUsers]
result.forEach(u => {
idsToReplace[u.id] = true
})
userCategory.forEach(u => {
if(!idsToReplace[u.id]){
result.push(u)
}
})
console.log(result)

How to filter an array of objects with names from another array of objects [duplicate]

This question already has answers here:
Filter array of objects with another array of objects
(11 answers)
Closed 2 years ago.
I'm new to Javascript and I'm struggling with how to use the map, filter, find and other functions. I have two arrays of objects, and I wanted to filter the first one with the second.
const users = [
{ name: 'Anna', age: 22, gender: 'F' },
{ name: 'John', age: 25, gender: 'M' },
{ name: 'Mary', age: 27, gender: 'F' },
{ name: 'Joe', age: 30, gender: 'M' }
]
const filter = [
{ name: 'Anna' },
{ name: 'John' }
]
// Here is the expected result:
const expected_result = [
{ name: 'Anna', age: 22, gender: 'F' },
{ name: 'John', age: 25, gender: 'M' }
]
Does anyone know what is the best way to do this?
something like this?
const filteredUsers = users.filter(user=>filter.find(x=>(x.name==user.name)&&(x.age==user.age)&&(x.gender==user.gender));
what would be better is to give everyone a unique id.
const filteredUsers = users.filter(user=>filter.find(x=>(x.id==user.id));
"What is the best way" is a matter of opinion, but if you would have a large filter object, then it makes sense to first convert it to a temporary set:
function filterBy(users, filter) {
let set = new Set(filter.map(({name}) => name)); // for faster lookup
return users.filter(({name}) => set.has(name));
}
// demo
const users = [{name: 'Anna',age: 22,gender: 'F',},{name: 'John',age: 25,gender: 'M',},{name: 'Mary',age: 27,gender: 'F',},{name: 'Joe',age: 30,gender: 'M',},];
const filter = [{name: 'Anna',},{name: 'John',}];
console.log(filterBy(users, filter));
const users = [{
name: 'Anna',
age: 22,
gender: 'F',
},
{
name: 'John',
age: 25,
gender: 'M',
},
{
name: 'Mary',
age: 27,
gender: 'F',
},
{
name: 'Joe',
age: 30,
gender: 'M',
},
];
const filter = [{
name: 'Anna',
},
{
name: 'John',
},
];
const result = users.filter(value => {
const isExist = filter.findIndex(data => data.name === value.name);
return isExist === -1 ? false: true;
});
console.log(result)

Comparing the properties of objects of two arrays and storing it in a new array

I would like to compare a property of an object of two arrays of different lengths. If my condition is true (gender check) and then if that property matches then I would like to combine the properties of that object from both arrays and store it in a different array.
For example:
// array 1
var array1 = [{name: 'Jan', age: 19, category: {gender: 'Male'}}, {name: 'Suzy', age: 29, category: {gender: 'Female'}}, {name: 'Peter', age: 39, category: {gender: 'Male'}}, {name: 'Bart', age: 49, category: {gender: 'Male'}}, {name: 'John', age: 59, category: {gender: 'Male'}}];
// array 2
var array2 = [{name:'Kean', job: 'Technician'},{name:'Nick', job:'Mathematics'},{name: 'Jan', job: 'Tester'}, {name: 'Suzy', job:'Developer'}, {name: 'Peter', job: 'Scrum master'}]
Expected result:
var resultMale = [{name: 'Jan', age: 19,job: 'Tester'}, {name: 'Peter', age: 39, job: 'Scrum master'}];
var resultFemale = [{name: 'Suzy', age: 29, job:'Developer'}];
Below is my attempt just to show that I have been putting all my effort to find a solution myself. I have changed all the functions and variable names
this.
xxxxxxxx.getContractsForRules().then(res => {
// res.xxxxxx.forEach(function (obj) {
// if(obj.contract.product.xxxxxxx=== 'xxxxxxx') {
// console.log(this.xxxxxx.xx);
// for(let i=0; i < this.xxxxxxx.length; i++) {
// if(obj.contract.accountNumber === this.xxxxxxxx[i].ibanNumber) {
// this.currentAccount = {
// accountNumber: res.xxxxx[i].contract.accountNumber,
// accountName: res.xxxxx[i].contract.customer.xxxxxx
// };
// this.xxxxxxx.push(this.xxxxxx);
// }
// };
// }
// });
this.result = res.contractList.filter(item => this.allCurrentAccounts.);
if(res.xxxx[i].contract.xxxxx=== this.xxxxx[i].ibanNumber) {
this.savingAccount = {
accountNumber: xxxx.xxxx[i].contract.accountNumber,
accountName: res.xxxxx[i].contract.customer.xxxxx
};
this.xxxxx.push(this.xxxxx);
}
});
this.test();
}
What you finally need is an Intersection of both the arrays. So, you could do the following -
var array1 = [{ name: 'Jan', age: 19, category: { gender: 'Male' } }, { name: 'Suzy', age: 29, category: { gender: 'Female' } }, { name: 'Peter', age: 39, category: { gender: 'Male' } }, { name: 'Bart', age: 49, category: { gender: 'Male' } }, { name: 'John', age: 59, category: { gender: 'Male' } }];
var array2 = [{ name: 'Kean', job: 'Technician' }, { name: 'Nick', job: 'Mathematics' }, { name: 'Jan', job: 'Tester' }, { name: 'Suzy', job: 'Developer' }, { name: 'Peter', job: 'Scrum master' }];
// Empty arrays to contain final intersection array for both male & females
var resultMale = [], resultFemale = [];
/* now looping over both arrays to traverse all the elements from them */
// iterating over first array
array1.forEach(x => {
// iterating over second array
array2.forEach(y => {
// collect the objects only if the name attribute matches in both
if (x.name == y.name) {
// push into male array if gender is male else push into female array
if (x.category && x.category['gender'] == 'Male') {
resultMale.push({
name: x.name,
age: x.age,
job: y.job
});
} else if (x.category && x.category['gender'] == 'Female') {
resultFemale.push({
name: x.name,
age: x.age,
job: y.job
});
}
}
});
});
console.log(resultMale);
console.log(resultFemale);
Note - this can be optimized to reduce the time complexity.

How to replace existing array objects of one array to another array in javascript

var arr1 = [{
id: '111',
name: 'aaa'
}, {
id: '222',
name: 'bbb'
}, {
id: '333',
name: 'ccc'
}, {
id: '444',
name: 'ddd'
}];
var arr2 = [{
id: '111',
name: 'xyz'
}, {
id: '333',
name: 'abc'
}];
my requirement: I need to replace aar1 with arr2 having same id in arr2 but different name value.
Below Result i should get in arr1
var arr1 = [{
id: '111',
name: 'xyz'
}, {
id: '222',
name: 'bbb'
}, {
id: '333',
name: 'abc'
}, {
id: '444',
name: 'ddd'
}];
you can use map and find to replace arr2 name in arr1.
map function iterate through each elements of arr1, find will match both id and return matched object if found. if we don't find we will just return arr1 item using || operator.
const result = arr1.map(item => arr2.find(item2 => item.id === item2.id) || item)
Working example:
var arr1 = [{
id: '111',
name: 'aaa'
}, {
id: '222',
name: 'bbb'
}, {
id: '333',
name: 'ccc'
}, {
id: '444',
name: 'ddd'
}];
var arr2 = [{
id: '111',
name: 'xyz'
}, {
id: '333',
name: 'abc'
}];
const result = arr1.map(item => arr2.find(item2 => item.id === item2.id) || item)
console.log(result)
This is my interpretation of the question.
Only copy the name if the id is found in arr2.
arr1.forEach(e1 => {
var e2 = arr2.find( e => e.id === e1.id );
if (e2) { e1.name = e2.name; }
});

How to Flatten Object Underscore with a new Property?

I'm having an array of this:
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
]
How can I use underscore to flatten the age object in the array. The expected result is:
arr == [
{
name: 'John',
age: 'less than 19'
},
{
name: 'Doe',
age: 'more than 19'
}
];
Thanks,
You can try this:
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
Demo:
var arr = [{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
}, {
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}];
var result = arr.map(function(item) {
return {
name: item.name,
age: item.age.value
};
});
console.log(result);
I hope this will help you.
using old style :D
var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
];
var newArr = [];
arr.forEach(function(item, idx) {
newArr.push({
name: item.name,
age: item.age.value
});
});
console.log(newArr);

Categories

Resources