Javascript Array add or update - javascript

Javascript Array push issue
I have a object:
people: [{name: peter, age: 27, email:'peter#abc.com'}]
I want to push:
people.push({
name: 'John',
age: 13,
email: 'john#abc.com'
});
people.push({
name: 'peter',
age: 36,
email: 'peter#abc.com'
});
The finally I want is:
people: [
{name: 'peter', age: 36, email:'peter#abc.com'},
{name: 'john', age: 13, email:'john#abc.com'},
]
I dont have any key but the email is a unique

You can also do like this by generating an Array method. It takes two arguments. First one designates the object to push and the second is the unique property to check to replace if a previously inserted item exists.
var people = [{name: 'peter', age: 27, email:'peter#abc.com'}];
Array.prototype.pushWithReplace = function(o,k){
var fi = this.findIndex(f => f[k] === o[k]);
fi != -1 ? this.splice(fi,1,o) : this.push(o);
return this;
};
people.pushWithReplace({name: 'John', age: 13, email: 'john#abc.com'}, "email");
people.pushWithReplace({name: 'peter', age: 36, email: 'peter#abc.com'},"email");
console.log(people);

There is no "update" method as is in JavaScript.
What you have to do, is simply looping through your array first to check if the object is already inside.
function AddOrUpdatePeople(people, person){
for(var i = 0; i< people.length; i++){
if (people[i].email == person.email){
people[i].name = person.name;
people[i].age = person.age;
return; //entry found, let's leave the function now
}
}
people.push(person); //entry not found, lets append the person at the end of the array.
}

Related

Return only some keys from an array of objects

I want to display the array but only with name and age
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
let userList = users.map(users => {name: users.name, users.instrument })
console.log(userList);
didn't work. I'm missing a return somewhere right?
You should wrap the object statement in each iteration with ().
Also, I prefer using Destructuring assignment:
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var new_users = users.map(({name,instrument}) => ({name, instrument}));
console.log(new_users);
You just need to wrap object inside ()
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
var result = users.map(user => ({ name: user.name, instrument: user.instrument }));
console.log(result)
You forgot an = when setting users.
Inside the map function, you called the run-through-object users but use user.
You forgot an ' after 'guitar
You didn't set the key for the instrument value in the mapping function
You need to add brackets () around the object in the mapping function as it will be treated as arrow function if forgotten
In the end it should look like this:
const users = [{name: 'john', age: 20, instrument: 'guitar'}, {name: 'mary', age: 20, instrument: 'piano'}];
const mapped = users.map(user => ({name: user.name, instrument: user.instrument}));
console.log(mapped);

JavaScript: Comparing two objects

I want to compare two objects to make a new object.
original = [
{id: "A1", name: "Nick", age: 20, country: 'JP', code: 'PHP'}
]
edited = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", name: "Nick", age: 25, country: 'US', code: 'PHP'}
]
Compare two objects ('original' and 'edited')
If 'id' is set, compare the same ids' data, and take the data from 'edited', and get ONLY the 'id' and the data that is edited.
If 'id' is not set keep the whole data
The final object I want is like below;
final = [
{name: "Mike", age: 30, country: 'US'},
{id: "A1", age: 25, country: 'US'}
]
I've been trying this using filter, but I can't get desired result...
Try with Array#reduce .
Updated with all key pair match
Validate the edited array id value is available in original array using Array#map and indexOf function
If not push entire object to new array
First recreate the original array to object format like {key:[value]}
Then match each key value pair match or not with forEach inside the reduce function
var original = [{id: "A1", name: "Nick", age: 20, country: 'JP'}];
var edited = [{name: "Mike", age: 30, country: 'US'},{id: "A1", name: "Nick", age: 25, country: 'US'}];
var ids_org = Object.keys(original[0]).reduce((a,b,c)=> (a[b]=original.map(a=> a[b]),a),{});
var res = edited.reduce((a, b) => {
if (b.id) {
Object.keys(b).forEach(i=>{
if(ids_org[i].indexOf(b[i]) > -1 && i != 'id')
delete b[i];
})
a.push(b);
} else {
a.push(b);
}
return a;
}, []);
console.log(res)
use de structuring to extract out id from the object.
use lodash isEqual method to compare and later add back the id to the object.

How can I filter an array of objects with a value from another object?

I want to write a function which takes an array of objects with certain key value pairs as the first argument. And an object with key value pairs as the second argument.
The function should check if the key value pairs from the second argument are found in the array of objects from the first argument.
If so, it should return an array of objects which have the matching name and value pairs.
For example, if I have an array of objects (first argument):
[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
And as the second argument:
{age: 17}
It should return:
[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
Because of the matching value age
This is what I have come up with but don't know what to put in the for...in loop:
function checkTheName(list, check) {
let newArr = [];
for(let i = 0; i < list.length; i++){
for(let key in list[i]){
// Stuck here
}
}
return newArr;
}
You can do this with filter and every methods.
let a = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
let b = {age: 17}
function checkTheName(list, check) {
return list.filter(o => Object.keys(check).every(k => {
return (k in o) && check[k] == o[k]
}))
}
console.log(checkTheName(a, b))
A simple ES6 version with Array.prototype.filter and Array.prototype.every:
const data = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}];
const fObj = {age: 17};
const filtred = data.filter(item =>
Object.keys(fObj).every(k => item.hasOwnProperty(k) && item[k] === fObj[k])
);
console.log(filtred);
You can loop over the array and test for that property:
function checkTheName(check, list){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array =[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon",
age: 17}, {namenter code heree: "Poopy", age: 17}]
;
var resultObject = checkTheName( array,"string 1");
Use filter to loop over the array.
function findByAge(myArr, obj){
myArr.filter( (item) => {
if(obj.age === item.age){
return item
}
})
}
This will return an array with just the array items that you are looking for.
You can call it following line. Since the function returns a new array. We need to give the new array a name (newArray in this example).
var newArray = findByAge(myArr, obj)
You need to put an if condition comparing the age value of your check object with the age value of the list object. In case, both the values are equal, push object in newArr.
let list = [{ name: "Peter", age: 21 }, { name: "Kate", age: 18 }, { name: "Tihon", age: 17 }, { name: "Poopy", age: 17 }],
check = { age: 17 };
function checkTheName(list, check) {
let newArr = [];
for (let i = 0; i < list.length; i++) {
if (list[i].age == check.age) {
newArr.push(list[i]);
}
}
return newArr;
}
console.log(checkTheName(list, check));
Alternatively, you can also use array#filter.
let list = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}],
check = {age: 17},
result = list.filter(o => o.age === check.age);
console.log(result);
var filterobj ={age:17};
var data=[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
var newArray = data.filter(function (el) {
return el.age ==filterobj.age;
}

how to use variable for property in indexOf inside map function in Javascript

I have a function as below:
getValue(param) {
var result = [];
result = this.state.ObjectsData.map(x => {
if (result.indexOf(x.param) === -1) {
result.push(x.param)
}
});
}
//ObjectsData is array of objects
ObjectsData = [
{tag: 23, name: vicky, gender: m},
{tag: 13, name: sam, gender: m},
{tag: 23, name: raj, gender: m}
]
//x can be any object like below:
x = {tag: 23, name: vicky, gender: m}
param is the propertyName like tag
I am getting param as undefined at the below line even though the param has some value before map and after map at line
if (result.indexOf(x.param) === -1) { }
I am trying to find unique values for any property like:
for tag: 23, 13. And yes, x.tag or x.name or x.gender works fine but I want to make propertyName dynamic
You want to dynamically check the key whose name is the value of param, so instead of
if (result.indexOf(x.param) === -1) {
result.push(x.param)
}
Which checks for the key named param, you want
if (result.indexOf(x[param]) === -1) {
result.push(x[param])
}
Which checks for key with the name of the value of param
ObjectsData = [
{tag: 23, name: 'vicky', gender: 'm'},
{tag: 13, name: 'sam', gender: 'm'},
{tag: 30, name: 'raj', gender: 'm'}
]
result = _.map(ObjectsData,'tag'); //[23, 13, 30], use indexof result!
if(result.indexOf(23)===-1)
result = 'not found';
else
result = 'found';

Need to add a string to the end of first names in an array using lodash

I have the following array.
var gillFamily = [
{ name: 'john', age: 20 },
{ name: 'richard', age: 27 },
{ name: 'debbie', age: 55 },
{ name: 'dan', age: 25 },
{ name: 'robin', age: 60 }
];
I need to print the names with the lastname "Gill" added to them using lodash.
I've tried this which was the closest I got:
_.map(gillFamily, "name") + " Gill";
but that only adds Gill to the last name in the array.
How do I add the name to all items in the array?
One option is:
_.map(gillFamily, (el) => el.name + " Gill");
In case that the environment doesn't support ES6:
_.map(gillFamily, function(el) {
return el.name + " Gill"
});
You could also use Array.prototype.map function.
You need to access the name property inside the Object and then add the Gill string to that name.
var gillFamily = [ {name: 'john', age: 20},
{name: 'richard', age: 27},
{name: 'debbie', age: 55},
{name: 'dan', age :25},
{name: 'robin', age : 60}];
var gillFamilyWithLastNameAdded = _.map(gillFamily, person => person.name + " Gill");
console.log(gillFamilyWithLastNameAdded);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Using the map function you can map each element with the last name appended to using the following. Using _.each(), you can loop over the array of objects and update the property/properties desired. This probably may not be the best/most efficient technique but it's the best I could find by just reading the docs.
Note: This will overwrite the original object.
Disclaimer: I'm not an active lodash user.
// Setup example data
var gillFamily = [{
name: 'john',
age: 20
}, {
name: 'richard',
age: 27
}, {
name: 'debbie',
age: 55
}, {
name: 'dan',
age: 25
}, {
name: 'robin',
age: 60
}];
// Display the initial values
document.getElementById("start").innerText = JSON.stringify(gillFamily);
// Append family name on the current family member's name
var gillFamilyWithLastNames = _.each(gillFamily, function(el) {
// Append 'Gill' to the end of the existing name
el.name += ' Gill';
});
// Show the results
document.getElementById("end").innerText = JSON.stringify(gillFamilyWithLastNames);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<p>Starting Data</p>
<pre id="start"></pre>
<p>Ending Data</p>
<pre id="end"></pre>

Categories

Resources