How can I combine two object in javascript? - javascript

my first object like this :
{id: 1, quantity: 10, address: {id: 2, name: "stamford bridge", city: "london"}}
my second object like this :
{data: {id: 2, quantity: 20, address: {id: 4, name: "old traford", city: "manchester"}}, expired: "2017-08-16T06:46:02.566Z"}
I want to combine the object
How can I do it?

How can I merge properties of two JavaScript objects dynamically?
This method can combine the properties of two objects together.
Object.assign(obj1, obj2);
Or you have to change your data structure, if you're thinking about arrays.
var x = {id: 1, quantity: 10, address: {id: 2, name: "stamford bridge", city: "london"}}
and
var y = {data: [{id: 2, quantity: 20, address: {id: 4, name: "old traford", city: "manchester"}}], expired: "2017-08-16T06:46:02.566Z"}
Then you
y.data.push(x)

we can use the Object.assign(obj1, obj2); function to merge or else please add the sample output format you are expecting
var x={id: 1, quantity: 10, address: {id: 2, name: "stamford bridge", city: "london"}}
var y={data: {id: 2, quantity: 20, address: {id: 4, name: "old traford", city: "manchester"}}, expired: "2017-08-16T06:46:02.566Z"}
var z = Object.assign(x, y);
console.log(z)
console.log(z.id)
console.log(z.data)
console.log(z.data.id)

Related

Filter an array of objects with multiple elements with their values using javascript or lodash

I have an array of object as below.
const data =
[
{id: 1, name: 'Peter',age: 21, gender: 'Male'},
{id: 2, name: 'Steve',age: 24, gender: 'Male'},
{id: 3, name: 'John',age: 21, gender: 'Male'},
{id: 4, name: 'Julie',age: 26, gender: 'Female'}
]
I want to dynamically filter the above array with multiple elements with their values using javascript or lodash. If i add more elements to the object and try to filter with the same, the code should work fine. I'm expecting to pass the elements which needs to be filtered and the corresponding values, from an object as below.
const filter = {'name':'e','gender':'mal'}
Expected Output:
[{id: 1, name: 'Peter',age: 21, gender: 'Male'},
{id: 2, name: 'Steve',age: 24, gender: 'Male'},
{id: 4, name: 'Julie',age: 26, gender: 'Female'}]
You could filter by using the entries and Array#every for using all filters or Array#some for having only one filter property of the object.
const
data = [{ id: 1, name: 'Peter', age: 21, gender: 'Male' }, { id: 2, name: 'Steve', age: 24, gender: 'Male' }, { id: 3, name: 'John', age: 21, gender: 'Male' }, { id: 4, name: 'Julie', age: 26, gender: 'Female' }],
filter = { name: 'Pe', gender: 'Mal' },
filters = Object.entries(filter),
result1 = data.filter(o => filters.every(([k, v]) => o[k].includes(v))),
result2 = data.filter(o => filters.some(([k, v]) => o[k].includes(v)));
console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Use Object.entries to separate the keys and values from the filter object, find the value by using the key and lowerCase that value since you don't differentiate between uppercase and lowercase letters
const data =
[
{id: 1, name: 'Peter',age: 21, gender: 'Male'},
{id: 2, name: 'Steve',age: 24, gender: 'Male'},
{id: 3, name: 'John',age: 21, gender: 'Male'},
{id: 4, name: 'Julie',age: 26, gender: 'Female'}
]
const filter = {
'name': 'e',
'gender': 'mal'
}
const result = data.filter(x => Object.entries(filter)
.every(([key, val]) => x[key].toString().toLowerCase().includes(val)))
console.log(result)

JSON-server. Filter by nested value

I have DB (use json-server) like this:
DB = {
products: [
{id: 0, name: 'aaa', price: 10},
{id: 1, name: 'bbb', price: 20},
{id: 2, name: 'ccc', price: 50},
{id: 3, name: 'ddd', price: 1}
]
};
And array of ids:
cartItemsIds: [0, 3];
How can I get array of objects from DB with ids from cartItemsIds ?
Solved. If anyone needs:
`products?id=${cartItemsIds.join('&id=')}`
You can loop over your products from db like so:
for(const product of DB.products) {
if(cartItemsIds.includes(product.id)) {
console.log(product);
}
}

How to remove some elements in an object array using Lodash

I'll just ask on how to remove some elements in an object array using lodash.
var fruits = [
{ id: 1, name: 'Apple', price: 55, qty: 3, status: 'ripe' },
{ id: 2, name: 'Banana', price: 55, qty: 4, status: 'ripe' },
{ id: 3, name: 'Pineaple', price: 55, qty: 2, status: 'ripe' }
];
How will I remove the qty and status in all object array so it will look like this
[
{ id: 1, name: 'Apple', price: 55 },
{ id: 2, name: 'Banana', price: 55 },
{ id: 3, name: 'Pineaple', price: 55 }
]
Without any library, you can use map and destructure the object.
var fruits = [{"id":1,"name":"Apple","price":55,"qty":3,"status":"ripe"},{"id":2,"name":"Banana","price":55,"qty":4,"status":"ripe"},{"id":3,"name":"Pineaple","price":55,"qty":2,"status":"ripe"}]
var result = fruits.map(({qty,status,...r}) => r);
console.log(result);
You can do it without using a library too.
Use Array.map
var fruits = [{ id: 1, name: 'Apple', price: 55, qty: 3, status: 'ripe' },{ id: 2, name: 'Banana', price: 55, qty: 4, status: 'ripe' },{ id: 3, name: 'Pineaple', price: 55, qty: 2, status: 'ripe' }];
let result = fruits.map(({status,qty,...rest}) => rest);
console.log(result);
You can just iterate through the object using forEach and delete
the unwanted fields with the plain old delete operator.
This method cleans your current object, Without the need for a new object to be defined.
fruits.forEach((val) => {delete val.qty; delete val.status})
It is true that you don't need to use a library to effectively delete properties of an object though if you want to use lodash here is an example of how you would do that by using the .pick method:
let pickedFruits = [];
for (let i in fruits) {
pickedFruits.push(_.pick(fruits[i], ["id", "name", "price"]));
}
where pickedFruits will be the new array of objects each having an id, name and a price property.

How can I convert normal array of objects to multilevel array in javascript? [duplicate]

This question already has answers here:
Build tree array from flat array in javascript
(34 answers)
Closed 4 years ago.
My normal array object like this :
var b = [
{id: 1, name: 'England',parent_id: null},
{id: 2, name: 'Spain',parent_id: null},
{id: 3, name: 'Chelsea',parent_id: 1},
{id: 4, name: 'Manchester United',parent_id: 1},
{id: 5, name: 'Real Madrid',parent_id: 2},
{id: 6, name: 'Barcelona',parent_id: 2},
{id: 7, name: 'Hazard',parent_id: 3},
{id: 8, name: 'Morata',parent_id: 3},
{id: 9, name: 'Pogba',parent_id: 4},
{id: 10, name: 'Lukaku',parent_id: 4},
{id: 11, name: 'Ronaldo',parent_id: 5},
{id: 12, name: 'Bale',parent_id: 5},
{id: 13, name: 'Messi',parent_id: 6},
{id: 14, name: 'Suarez',parent_id: 6},
];
I want to convert the object array to be like this :
var b = [
{
name: 'England',
children: [
{
name: 'Chelsea',
children: [
{name: 'Hazard'},
{name: 'Morata'}
]
},
{
name: 'Manchester United',
children: [
{name: 'Pogba'},
{name: 'Lukaku'}
]
}
]
},
{
name: 'Spain',
children: [
{
name: 'Real Madrid',
children: [
{name: 'Ronaldo'},
{name: 'Bale'}
]
},
{
name: 'Barcelona',
children: [
{name: 'Messi'},
{name: 'Suarez'}
]
},
]
}
];
It seems it will be separated using key parent_id
But i'm still confused to implement it
How can I convert the array object like that?
Please help me guys
.filter() the b so it contains only items with parent_id: null
.map() remaining items, assigning children to them
.map() children for each of the root level parents to return them without parent_id field (optional, not in the example)
var b = [
{id: 1, name: 'England',parent_id: null},
{id: 2, name: 'Spain',parent_id: null},
{id: 3, name: 'Chelsea',parent_id: 1},
{id: 4, name: 'Manchester United',parent_id: 1},
{id: 5, name: 'Real Madrid',parent_id: 2},
{id: 6, name: 'Barcelona',parent_id: 2},
{id: 7, name: 'Hazard',parent_id: 3},
{id: 8, name: 'Morata',parent_id: 3},
{id: 9, name: 'Pogba',parent_id: 4},
{id: 10, name: 'Lukaku',parent_id: 4},
{id: 11, name: 'Ronaldo',parent_id: 5},
{id: 12, name: 'Bale',parent_id: 5},
{id: 13, name: 'Messi',parent_id: 6},
{id: 14, name: 'Suarez',parent_id: 6},
];
const done = b.filter(person => !person.parent_id).map(person => {
return {
id : person.id,
name : person.name,
children: b.filter(child => child.parent_id == person.id)
}
});
console.log(done);

Combining objects on two arrays based on commonly shared ids

I have two arrays that contain objects. Objects on the first array contain an id, name and age.
I have tried many answers that I have found on StackOverflow such as this one and this one and elsewhere online, however it is proving quite tricky and I am unable to get this working.
var arrOne = [
{id: 1, name: 'Raul', age: 18},
{id: 2, name: 'Sarah', age: 20},
{id: 3, name: 'Sanchez', age: 30}
];
The second array contains an id that is related to the users in the first array and and an associated image.
var arrOne = [
{id: 1, image: 'raulrod.jpg'},
{id: 2, image: 'saz.jpg'},
{id: 1, image: 'hola.jpg'},
{id: 3, image: 'qtal.jpg'},
{id: 1, image: 'senor.jpg'},
{id: 3, image: 'ciao.jpg'},
];
After they are combined I am looking for a result like this with each object combining the objects in both arrays based on the id.
var finalArr = [
{id: 1, name: 'Raul', age: 18 image: 'raulrod.jpg'},
{id: 1, name: 'Raul', age: 18 image: 'hola.jpg'},
{id: 1, name: 'Raul', age: 18 image: 'senor.jpg'},
{id: 2, name: 'Raul', age: 20 image: 'saz.jpg'}
{id: 3, name: 'Raul', age: 30 image: 'ciao.jpg'},
{id: 3, name: 'Raul', age: 30 image: 'qtal.jpg'},
];
With plain ES6, you could map the a new object with the properties of arrOne and, with Array#find, the properties of the related object of arrTwo.
If needed, you could later sort the result by id.
var arrOne = [{ id: 1, name: 'Raul', age: 18 }, { id: 2, name: 'Sarah', age: 20 }, { id: 3, name: 'Sanchez', age: 30 }],
arrTwo = [{ id: 1, image: 'raulrod.jpg' }, { id: 2, image: 'saz.jpg' }, { id: 1, image: 'hola.jpg' }, { id: 3, image: 'qtal.jpg' }, { id: 1, image: 'senor.jpg' }, { id: 3, image: 'ciao.jpg' }],
result = arrTwo.map(a => Object.assign({}, a, arrOne.find(b => a.id === b.id)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use array.map and array.find proptotypes:
var arrOne = [
{id: 1, name: 'Raul', age: 18},
{id: 2, name: 'Sarah', age: 20},
{id: 3, name: 'Sanchez', age: 30}
];
var arrTwo = [
{id: 1, image: 'raulrod.jpg'},
{id: 2, image: 'saz.jpg'},
{id: 1, image: 'hola.jpg'},
{id: 3, image: 'qtal.jpg'},
{id: 1, image: 'senor.jpg'},
{id: 3, image: 'ciao.jpg'}
];
var finalArr = arrTwo.map(item => {
var correspondingObj = arrOne.find(obj => obj.id === item.id)
item.name = correspondingObj.name;
item.age = correspondingObj.age;
return item;
});
console.log(finalArr);
Actually, https://stackoverflow.com/a/19480257/5809250 should help you.
Have you included underscore - http://underscorejs.org/#extend?
If you do not want to include underscore, you may use [assign][3] function.
Also, I wrote the example. It is not so perfect so you may try to improve it by yourself.

Categories