Return new form of arrays - javascript - javascript

My data:
{
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
},
{
"id": 7,
"code": "airtel121",
"position": null,
"salary": null,
"login": {
"id": 8,
"username": "annamalai",
"firstName": "Anna",
"lastName": "malai",
"code": "airtel121",
}
}
]
}
My expected outcome:
{
"rows": [
{
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
"staffs": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
}
]
},
{
"id": 8,
"username": "annamalai",
"firstName": "Anna",
"lastName": "malai",
"code": "airtel121",
"staffs": [
{
"id": 7,
"code": "airtel121",
"position": null",
"salary": null",
}
]
}
]
}
I tried, but only i am getting first object, check my fiddle:
http://jsbin.com/qaqehakuwi/edit?js,output
Is this possible to loop using for loop or it can be done by lodash?
Check my above jsbin link for code.
I am using ES6 way of code in my project, so i used spread operator.

You can use map to create the rows array of the new object from the rows array of the old one:
let newObj = {
rows: oldObj.rows.map(row => { // map the rows of the old object into the rows of the new object
let { login, ...rest } = row; // for each object/row get the login object as 'login' and the rest of the props as 'rest'
return { ...login, staffs: [rest] }; // return a new object that has the props of 'login' and an additional prop 'staffs' which is an array containing 'rest'
})
};
Example:
let oldObj = {"rows":[{"id":3,"code":"airtel121","position":"manager","salary":"25000","login":{"id":4,"username":"sameer","firstName":"Mohamed","lastName":"Sameer","code":"airtel121"}},{"id":7,"code":"airtel121","position":null,"salary":null,"login":{"id":8,"username":"annamalai","firstName":"Anna","lastName":"malai","code":"airtel121"}}]};
let newObj = {
rows: oldObj.rows.map(row => {
let { login, ...rest } = row;
return { ...login, staffs: [rest] };
})
};
console.log(newObj);

Related

Object with nested array to filter, want to return entire object with new filtered array

I'm attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:
{
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 3,
"lastName": "Weaver",
"firstName": "Sigourney"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
and what I'm doing right now is
const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);
but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):
{
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
I've tried reading around but I'm not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!
If you want to mutate the existing object, just assign the result of the .filter to the .actors property.
movie.actors = movie.actors.filter((actor) => actor.id !== id);
console.log(movie);
If you want to keep the existing object unmutated, spread the rest of the properties into a new object while filtering.
const updatedMovie = {
...movie,
actors: movie.actors.filter((actor) => actor.id !== id)
};
console.log(updatedMovie);
const movies = {
"id": 1,
"title": "Avatar",
"movieLength": 162,
"releaseDate": "2009-12-18",
"trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
"genre": {
"id": 1,
"genre": "Action"
},
"rating": {
"id": 3,
"rating": "PG-13"
},
"director": {
"id": 1,
"lastName": "Cameron",
"firstName": "James"
},
"actors": [
{
"id": 2,
"lastName": "Worthington",
"firstName": "Sam"
},
{
"id": 3,
"lastName": "Weaver",
"firstName": "Sigourney"
},
{
"id": 4,
"lastName": "Saldana",
"firstName": "Zoe"
}
],
"comments": []
}
const id = 3; // or any other id you want
const actors = movies.actors.filter(actor => actor.id != id)
const newMovies = Object.assign({}, movies , { actors })
console.log(newMovies)

how to remove sessionID:null value objects from the array nested inside the array of objects in js

[
{
"_id": "5edfb4e587a1873120735dcf",
"firstname": "abc",
"lastname": "abc",
"sessions": [
{
"_id": "5efc68d146d8330a449e7108",
"sessionID": null
},
{
"_id": "5efc68e646d8330a449e710a",
"sessionID": null
}
]
},
{
"_id": "5eedf5685bdb7d33c83186e7",
"firstname": "sam",
"lastname": "ple",
"sessions": [
{
"_id": "5efc692d46d8330a449e710c",
"sessionID": null
}
]
},
{
"_id": "5ef04df83e41dd5b78fe6908",
"firstname": "User",
"lastname": "name1",
"sessions": [
{
"_id": "5efc6a8846d8330a449e710e",
"sessionID": null
},
{
"_id": "5efc6abd46d8330a449e7110",
"sessionID": null
}
]
},
{
"_id": "5efe0d0c7300073244d765d9",
"sessions": [],
"firstname": "User",
"lastname": "name1"
}
]
You need to map over your array and filter out sessions with null
let originalArray = [
{
"_id": "5edfb4e587a1873120735dcf",
"firstname": "abc",
"lastname": "abc",
"sessions": [
{
"_id": "5efc68d146d8330a449e7108",
"sessionID": null
},
{
"_id": "5efc68e646d8330a449e710a",
"sessionID": null
}
]
},
.... the rest of your orignal object
]
let newArray = originalArray.map(item => {
let sessions = item.sessions.filter(session => {
return session.sessionID !== null
})
return {
...item,
sessions
}
})

sort array in javascript base on the external id

I have an array of users and each user has a unique id. I want to sort this array by comparing with my currentUser so I can have my current user in the first place inside the array and all others after that(alphabetically)
how can I do that in javascript?
Thanks
const currentuser = "f8a0b09c-ea3e-4f33-9c01-c16200f6ce1b";
const lists = [
{
"name": "Mahdieh Hosseiny",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "eb6433d3-11e8-4660-82fa-3f53cca569f4"
},
{
"name": "Ahmad Dehnavi",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "dc21291c-34bc-4363-b733-cbc405ba2eab"
},
{
"name": "Staff 4 Worrell",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "a3738c05-d6fb-4fb2-90ef-98d0b71939c5"
},
{
"name": "Amir Hossein",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "c1a70e04-992e-4509-8271-29efe3f6813b"
},
{
"name": "Hormoz Javadi",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "c9dbbb02-7179-4137-87df-f080cd5b7400"
},
{
"name": "westscityclub verify",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "25b93407-7b0d-4639-a758-0c7e40a88dc4"
},
{
"name": "Tina Worrell",
"avatar": "savatar.jpg",
"id": "f8a0b09c-ea3e-4f33-9c01-c16200f6ce1b"
}
]
This will ouput the result array in which the correspoding object will be the first, and others will be sorted by name prop:
[
...lists.filter((item) => item.id === currentuser),
...lists.filter((item) => item.id !== currentuser).sort((a, b) => a.name.localeCompare(b.name)),
]
const currentuser = "f8a0b09c-ea3e-4f33-9c01-c16200f6ce1b";
const lists = [
{
"name": "Mahdieh Hosseiny",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "eb6433d3-11e8-4660-82fa-3f53cca569f4"
},
{
"name": "Ahmad Dehnavi",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "dc21291c-34bc-4363-b733-cbc405ba2eab"
},
{
"name": "Staff 4 Worrell",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "a3738c05-d6fb-4fb2-90ef-98d0b71939c5"
},
{
"name": "Amir Hossein",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "c1a70e04-992e-4509-8271-29efe3f6813b"
},
{
"name": "Hormoz Javadi",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "c9dbbb02-7179-4137-87df-f080cd5b7400"
},
{
"name": "westscityclub verify",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "25b93407-7b0d-4639-a758-0c7e40a88dc4"
},
{
"name": "Tina Worrell",
"avatar": "savatar.jpg",
"id": "f8a0b09c-ea3e-4f33-9c01-c16200f6ce1b"
}
];
console.log([
...lists.filter((item) => item.id === currentuser),
...lists.filter((item) => item.id !== currentuser).sort((a, b) => a.name.localeCompare(b.name)),
]);
You should use Array.sort() method. It accepts function that will be used to sort items. What is worth mentioning it will sort array in place (after calling it list will stay sorted, it does not copy it):
const currentuser = "f8a0b09c-ea3e-4f33-9c01-c16200f6ce1b";
const lists = [
{
"name": "Mahdieh Hosseiny",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "eb6433d3-11e8-4660-82fa-3f53cca569f4"
},
{
"name": "Ahmad Dehnavi",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "dc21291c-34bc-4363-b733-cbc405ba2eab"
},
{
"name": "Staff 4 Worrell",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "a3738c05-d6fb-4fb2-90ef-98d0b71939c5"
},
{
"name": "Tina Worrell",
"avatar": "savatar.jpg",
"id": "f8a0b09c-ea3e-4f33-9c01-c16200f6ce1b"
},
{
"name": "Amir Hossein",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "c1a70e04-992e-4509-8271-29efe3f6813b"
},
{
"name": "Hormoz Javadi",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "c9dbbb02-7179-4137-87df-f080cd5b7400"
},
{
"name": "westscityclub verify",
"avatar": "/static/media/defaultAvatar.95bdd942.svg",
"id": "25b93407-7b0d-4639-a758-0c7e40a88dc4"
}
]
function compare(a, b) {
if (a.id == currentuser) return -1
if (b.id == currentuser) return 1
return a.name.localeCompare(b.name)
}
lists.sort(compare) //from now lists is sorted.
console.dir(lists.map(s => s.name))
you want your currentuser element at first position. so one way is to use custom sorting of array. see here how sort function works.
lists.sort(function(u1,u2) { return u1.id == currentuser ? -1: u1.id.localCompare(u2.id); });

Object not replacing using spread operator

I want to replace existing object with new updated fields using spread operator. But I am not getting the correct result.
Below are my two objects.
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
I can do it with .map. Below is my code.
let result = obj1.map(item => {
if (item.id === newObj.id) {
return {...item, ...newObj};
}
return item;
});
But I do not want to run the loop and want to acheive by spread operator only.
Example for spread. Which is not working. It's not replacing the object. Instead creating one more.
[...obj1, newObj];
Can someone help me?
JSBIN CODE SNIPPET
Spread syntax doesn't replace the object within array like you used it. Using map is the simplest and understandable way. However if you want to use spread syntax you would first need to find the index to be replaced and then use slice on array
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
const idx = obj1.findIndex(item => item.id === newObj.id);
obj1 = [...obj1.slice(0, idx), newObj, ...obj1.slice(idx + 1)];
console.log(obj1);
Use Object.assign
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
Object.assign(obj1[2], newObj);
console.log(obj1)
Using .find() to get the target obj
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
const targetObj = obj1.find(obj => obj.id === newObj.id)
Object.assign(targetObj, newObj);
console.log(obj1)
you should normalize your data by id this way:
obj1 = {
1: {
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
2: {
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
3: {
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
}
newObj = {
3: {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
}
this way you can use spread operator:
{ ...obj1, ...newObj }
in order to normalize you can use the reduce func this way:
const normalized = obj1.reduce((result, obj) => ({ ...result, [obj.id]: obj }), {})
Spread operator is magic but it won't do whatever you want, you will have to loop over and replace the object. Instead of doing a map(), I would prefer find(). The use Object.assign() to achieve what you want.
let obj1 = [
{
"id": 1,
"name": "Michel",
"age": 34,
"email": "michel#gmail.com"
},
{
"id": 2,
"name": "Abby",
"age": 40,
"email": "abby#gmail.com"
},
{
"id": 3,
"name": "Gary",
"age": 40,
"email": "abby#gmail.com"
}
]
let newObj = {
"id": 3,
"name": "Gary",
"age": 23,
"email": "gary#gmail.com"
}
let foundOb = obj1.find(e => e.id === newObj.id);
Object.assign(foundOb, newObj)
console.log(obj1)
You cannot use spread syntax in that way. One solution would be to find index of the object you want to replace by id property and then you could use spread syntax with slice method to create new array with replaced object.
let obj1 = [{"id":1,"name":"Michel","age":34,"email":"michel#gmail.com"},{"id":2,"name":"Abby","age":40,"email":"abby#gmail.com"},{"id":3,"name":"Gary","age":40,"email":"abby#gmail.com"}]
let newObj = {"id":3,"name":"Gary","age":23,"email":"gary#gmail.com"}
const index = obj1.findIndex(({id}) => id == newObj.id)
const result = [...obj1.slice(0, index), newObj, ...obj1.slice(index + 1)]
console.log(result)
I would do something like:
updatedObj = [obj1.map((entry) => entry.id !== newObj.id), newObj]
This would give me the updated object with minimal syntax

Adding object properties from one JSON data file to another

I have two local JSON files. I want to add the property of one object from one file to the corresponding object in the other file.
Here is an example..
Array1:
[
{
"id": 1,
"username": "Joe Smith",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 2,
"username": "Jane Smith",
"pic": "images/profile/Jane_smith.jpg"
}
]
Array2:
[
{
"id": 3,
"userId": 1,
"profession": "dentist"
},
{
"id": 4,
"userId": 2,
"profession": "pilot"
}
The idea is to add the "pic" property from Array1 to the correct object in Array2. If the id from Array1 matches the userId from Array2, it's a correct match. Array2 would end up looking like this:
[
{
"id": 3,
"userId": 1,
"profession": "dentist",
"pic": "images/profile/Joe_smith.jpg"
},
{
"id": 4,
"userId": 2,
"profession": "pilot",
"pic": "images/profile/Jane_smith.jpg"
}
Afterwards I'm going to use angular to display a name with the face. Hope I explained that ok. Any help would be much appreciated!
Just for the fun of it. In this example using https://lodash.com.
var people = [
{ "id": 1, "username": "Joe Smith", "pic": "images/profile/Joe_smith.jpg" },
{ "id": 2, "username": "Jane Smith", "pic": "images/profile/Jane_smith.jpg"},
{ "id": 3, "username": "I play too much games", "pic": "images/profile/toomuch.jpg"}
];
var professions = [
{ "id": 3, "userId": 1, "profession": "dentist" },
{ "id": 4, "userId": 2, "profession": "pilot" }
];
var workers = _.map(people, function(human) {
var work = _.findWhere(professions, { 'userId': human.id });
return _.extend(human, work ? work : { 'profession' : 'unemployed' });
});
console.log(workers);

Categories

Resources