How to update an object of objects using its id in JavaScript? - javascript

I have this object of objects and i want to update this object of objects using the id that each object have this is my code:
lists = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' }
}
function updateItem(id, property,value) {
return (lists[id] = { ...lists[id], [property]: value });
}
if i put it like this it works but i want to do it with just two parameters. Like this:
function updateItem(id, property) {
return (lists[id] = { ...lists[id], property);
}

If you are sure to call the update function with an object
lists = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' }
}
function updateItem({id, netWorth}) {
return (lists[id] = { ...lists[id], netWorth });
}
console.log(updateItem({id:'id3', netWorth: '$200M'} ))
Two ways you can do this:

OPTION 1
You can instead pass the id of the object, and pass a simple object representing a property with it's corresponding value like propertyObj= { propertyName: propertyValue}. And then spread that object within the main object defined by that id:
let lists = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' }
}
// You can pass an id, and a simple object updating the targeted property
function updateItem(id, propertyObj) {
lists[id] = { ...lists[id], ...propertyObj};
}
// test for the updateItem
updateItem("id3", {"name": "Steve Jobs"});
//Let's print and see if it was updated.
console.log(lists);
OPTION 2
Another option would be to associate the updateItem() function with the object itself and set it as a method, since we're dealing with properties, why not?
let list = {
id3: { id: 'id3', name: 'Capitan America', job: 'superHero' },
id4: { id: 'id4', name: 'Spider-man', job: 'Pro footballer' },
// let's defined update method that receive same params
update: function(id, propertiesObject){
this[id] = {...this[id], ...propertiesObject};
}
}
// Let's update the list using it's built-in update() method
list.update("id3", {"name": "Jeff Bezos"});
// Let's print the Updated list
console.log(list);
// NOTE: your object can have many properties in it that you wish to update in your original list.

Related

Functional Programming exercise I can't figure out

I've been looking at a problem for hours and failing to find a solution. I'm given an array of customer objects.
In each customer object is an array of friends.
In the array of friends is an object for each friend, containing some data, including a name key/value pair.
What I'm trying to solve for: I'm given this customers array and a customer's name. I need to create a function to find if this customer name is in any other customer's friend lists, and if so, return an array of those customer's names.
Below is a customer list. And as an example, one of the customers is Olga Newton. What the code should be doing is seeing that Olga Newton is a customer and is also in the friends lists of Regina and Jay, and should be returning an array of Regina and Jay.
I thought I could do this simply with a filter function, but because the friends list is an array with more objects, this is adding level of complexity for me I can't figure out.
Below is a customer array. The out put should be
['Regina', 'Jay']
and what I've gotten has either been
[{fullCustomerObj1}, {fullCustomerObj2}]
or
[ ]
What am I missing?
Here is the customer array:
var customers = [{
name: "Olga Newton",
age: 43,
balance: "$3,400",
friends: [{
id: 0,
name: "Justice Lara"
}, {
id: 1,
name: "Duke Patrick"
}, {
id: 2,
name: "Herring Hull"
}, {
id: 3,
name: "Johnnie Berg"
}]
}, {
name: "Regina",
age: 53,
balance: "$4,000",
friends: [{
id: 0,
name: "Cheryl Kent"
}, {
id: 1,
name: "Cynthia Wells"
}, {
id: 2,
name: "Gutierrez Waters"
}, {
id: 3,
name: "Olga Newton"
}]
}, {
name: "Jay",
age: 28,
balance: "$3,000",
friends: [{
id: 0,
name: "Cross Barnett"
}, {
id: 1,
name: "Raquel Haney"
}, {
id: 2,
name: "Olga Newton"
}, {
id: 3,
name: "Shelly Walton"
}]
}];
Use filter and map, please.
function friends(c, name){
return c.filter((a) => {
return a.friends.map(b => b.name).includes(name)
}).map(a => a.name);
}
console.log(friends(customers, "Olga Newton"));
// ['Regina', 'Jay']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
We look to an array (friends[]) inside anther (customers[]), So used two for loops, the first determine witch customer will look for his friends, and the second the array will search inside, then set if statement if the cust name is inside friends[]: adding the customer name to customerFriends[] array, At the end return the customerFriends[].
let cust = "Olga Newton"; // Get the customer name who you look for his friends.
const findFriend = (cust, arrs) => { // Create findFriend function.
let customerFriends = []; // Create an array to set the result to it.
for (let i = 0; i < arrs.length; i++) { // For each Customer.
for (const arr of arrs[i].friends) { // For each Friend.
if (arr.name === cust) { // Use Strict equality to find Customer name in friends[].
customerFriends.push(arrs[i].name); // Add the customer name to the customerFriends[].
}
}
}
return customerFriends;// Return the final results.
}
console.log(findFriend(cust, customers)); // Call the function.

Javascript: How to iterate through an array looking for an object value?

I have a js file that is just a an array with the name and type of person. I am trying to write a function in my other file to iterate through that array of objects and return just the object that matches a certain criteria. Here is my code.
person.js
export const persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
utils.js
// params initialized already
person_type = params.subType
const name = persons_options.map((option) => {
if(person_type === option.type){
return option.name
}
})
const person = name
The issue is I know map creates a new array so the output is ,,Phil. How would I just return one of the object names instead of all of them.
find() will do the work
let persons_options = [
{
name: 'Andrew',
type: 'Athlete',
},
{
name: 'Paul',
type: 'Worker',
},
{
name: 'Phil',
type: 'Developer',
},
]
let obj = persons_options.find(o => o.type === 'Developer');
//to return name
console.log("name",obj.name);
console.log(obj);
You need to use the find function.
See here the list of functions that you can call on an array:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods
filter might best suit your case if multiple results may be returned.

Sorting objects based on a string value property in TypeScript

I have an array of objects and the definition for an object looks something like this:
export class AccountInfo {
accountUid: string;
userType: string;
firstName: string;
middleName: string;
lastName: string;
}
NOTE: The reason I don't have userType as an enum is because the object is populated by a database call and I couldn't figure out a clean way to have the string returned from the db populate the enum.
I want to sort the array so that objects with a userType of 'STAFF' appear first, followed by 'TEACHER', then 'PARENT', then 'STUDENT'.
You can store the order in an array, then just use indexOf with sort to achieve your goal. See the code example below:
const humans = [{
accountUid: "1",
userType: "TEACHER",
}, {
accountUid: "2",
userType: "STAFF",
}, {
accountUid: "3",
userType: "STUDENT",
}, {
accountUid: "4",
userType: "PARENT",
}];
const order = ['STAFF', 'TEACHER', 'PARENT', 'STUDENT'];
const result = humans.sort((a, b) => order.indexOf(a.userType) - order.indexOf(b.userType));
console.log(result)
If you can't use ES6, just use:
humans.sort(function(a, b){
return order.indexOf(a.userType) - order.indexOf(b.userType);
});
Here is another way to do it, probably have an order object to store the orders
const actionOrder = {
"EAT" : 1,
"SLEEP" : 2,
"PLAY" : 3,
} as const;
const users = [{
name: "Mike",
action: "PLAY"
}, {
name: "John",
action: "EAT"
}, {
name: "Harry",
action: "SLEEP"
}
];
users.sort((a,b) => {
return actionOrder[a.action] - actionOrder[b.action];
});
console.log(users);

Compare value and add if matches to an array

Im trying to merge 2 data sources in 1, I wanna loop through them and if a specefic value matches than add it to the first object with the same value and add the in the emty array what is already there. No matter how much objects I have.
So lets say I have this information
Source 1
one = {
"teams": [
{
name: 'ABC',
members: [],
rooms: '0'
},
{
name: 'DEF',
members: [],
rooms: '1'
}
]
}
Source 2
two = {
"persons": [
{
name: 'Foo',
gender: 'male',
room: '1'
},
{
name: 'Bar',
gender: 'female',
room: '2'
}
]
}
And what I want is that the 'persons' array merge to the members array if the 'room and rooms' value matches.
What I would assume is something similar like this:
for(var i = 0 ; i < two.persons.length; i++) {
if (one.teams[i].rooms == two.persons[i].room) {
data.teams[i].members.push(two.persons[i]);
}
}
using higher order methods you can do:
one = {
"teams": [
{
name: 'ABC',
members: [],
rooms: '0'
},
{
name: 'DEF',
members: [],
rooms: '1'
}
]
};
two = {
"persons": [
{
name: 'Foo',
gender: 'male',
room: '1'
},
{
name: 'Bar',
gender: 'female',
room: '2'
}
]
};
var ttt = one.teams.map(function(x){
var roomVal= x.rooms;
x.members = two.persons.filter(function(t){
return t.room == roomVal});
return x;
})
one.teams = ttt;
console.log(one)
The problem with your code is that once you iterate the two array, then you do not go back and see if the previous element matched with the current one.
For example, if [0] on each arrays does not match and you iterate to index [1] in the for-loop, you do not have a way to check if two[1] matched one[0].
To do a complete search, you could directly iterate the arrays for each value of two:
two.persons.forEach(function(person) {
one.teams.forEach(function(team) {
if (team.rooms == person.room) {
team.members.push(person);
}
});
});
There are many strategies to do this. But most important you should iterate each array separately. I would use an Array.forEach();
one.teams.forEach(function (team, teamsIndex, teamsArray) {
two.persons.forEach(function (person, personsIndex, personsArray) {
if (team.room == person.room) {
// Do what you need to do.
}
});
});
Didn't check syntax so be aware to read Array.forEach(); documentation.

how do add to a key value to javascript object

I am trying to learn JS. It seems simple but I am not sure how to do this.
having this javascript object based on this good
thread
var people = {
1: { name: 'Joe' },
2: { name: 'Sam' },
3: { name: 'Eve' }
};
How do I add the following value 4: { name: 'John' }
To get name Eve I write
people["1"].name
Assign the anonymous object to it the way you would any other value.
people["4"] = { name: 'John' };
For what it's worth, since your keys are numeric you could also use zero-based indices and make people an array.
var people = [ { name: 'Joe' },
{ name: 'Sam' },
{ name: 'Eve' } ];
and
alert( people[2].name ); // outputs Eve
people[3] = { name: 'John' };
I think people should be an array :
var people = [
{ name: 'Joe' },
{ name: 'Sam' },
{ name: 'Eve' }
];
as the keys are integers, so you can add a person by :
people.push({name:'John'});
You can acces to the people by doing :
var somebody = people[1]; /// >>> Sam

Categories