2 Array combine into one array javascript - javascript

Here is two array one is firstName another is lastName
{
firstName: ['name1', 'name2'],
lastName: ['last1', 'last2'],
}
but I want to formate the data into one array like this.
{
"name": [{
"firstName": "name1",
"lastName": "last1"
},
{
"firstName": "name2",
"lastName": "last2"
},
]
}

Using Array#map:
const getNameObj = (data = {}) => {
const { firstName = [], lastName = [] } = data;
if(firstName.length !== lastName.length) return;
const name = firstName.map((fn, i) => (
{ firstName: fn, lastName: lastName[i] }
));
return { name };
};
console.log(
getNameObj({ firstName: [ 'name1', 'name2' ], lastName: [ 'last1', 'last2' ] })
);

You could loop through it using for...in and push each element inside new array like this example
const data = {
firstName: [ 'name1', 'name2' ],
lastName: [ 'last1', 'last2' ],
}
let newData = [];
for (let el in data.firstName){
newData.push({
firstName: data.firstName[el],
lastName: data.lastName[el],
})
}
console.log(newData)

You can use Array.reduce to get the result.
const input = {
firstName: [ 'name1', 'name2' ],
lastName: [ 'last1', 'last2' ],
};
const result = input.firstName.reduce((acc, firstName, index) => {
acc.name.push({
firstName: firstName,
lastName: input.lastName[index]
})
return acc
}, {'name': []})
console.log(result);

You can build a new object {name: <value>}, and set your <value> to a mapped version of the firstName array, where each firstName from your array is mapped to an object of the form {firstName: ..., lastName: ...}. Here the firstName key has a value that is the current name, and the lastName key has a value from the lastName array at the corresponding index:
const obj = { firstName: ['name1', 'name2'], lastName: ['last1', 'last2'], };
const res = {
name: obj.firstName.map((firstName, i) => ({firstName, lastName: obj.lastName[i]}))
}
console.log(res);

here it is:
let obj = {firstName: ['name1', 'name2'],lastName: ['last1', 'last2']};
let finalObj = {};
finalObj.name = []
for (let i = 0; i < obj.firstName.length; i++)
finalObj.name.push(
{
firstName: obj.firstName[i],
lastName: obj.lastName[i]
}
)

Related

How to get the value from an array and assign to array of objects?

I am trying to get the values from an array and assign to an array of objects as a new property.
The array of objects:
const employees = [
{
firstName: "Ana",
lastName: "Rosy"
},
{
firstName: "Zion",
lastName: "Albert"
},
{
firstName: "John",
lastName: "Doe"
}
];
An array
const ages = [30, 60, 45]
Desired result
const employees = [
{
firstName: "Ana",
lastName: "Rosy",
age:30
},
{
firstName: "Zion",
lastName: "Albert",
age:60
},
{
firstName: "John",
lastName: "Doe",
age:45
}
];
I tried something like this
const employeesWithAge = (ages) => {
return employees.map((row) => {
return {
...row,
age: ages
};
});
};
const result = employeesWithAge(ages);
console.log("result", result);
But it adds the entire array of ages to the employees array of objects.
Any help will be appreciated
You can use Array.prototype.map() for this. Use the spread syntax (...) on the current element to copy the properties into a new object, then add the age property based on the ages array, using .map() callback's second parameter (the current index).
employees.map((employee, i) => ({...employee, age: ages[i]}));
Live example:
const employees = [{
firstName: "Ana",
lastName: "Rosy"
},
{
firstName: "Zion",
lastName: "Albert"
},
{
firstName: "John",
lastName: "Doe"
}
];
const ages = [30, 60, 45];
const result = employees.map((employee, i) => ({ ...employee, age: ages[i] }));
console.log(result);
I think a simple for loop should solve your problem.
for (let i = 0; i < employees.length; i++) {
employees[i]["age"] = ages[i];
}
This loop iterates through the length of your list of employee objects and adds a new "age" attribute to each object with the corresponding age in your ages array.
All together I imagine your code looking something like this.
const employees = [
{
firstName: "Ana",
lastName: "Rosy"
},
{
firstName: "Zion",
lastName: "Albert"
},
{
firstName: "John",
lastName: "Doe"
}
];
const ages = [30, 60, 45];
for (let i = 0; i < employees.length; i++) {
employees[i]["age"] = ages[i];
}
console.log(employees);

Compare typescript objects and add diff to new object

Within my Angular application, I need to compare two typescript objects and create a new object that consists of key/value pairs where the value of the key is different in the second object.
Here is my code:
const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};
let newObj = {};
for(let key in objBefore) {
if (objBefore[key] !== objAfter[key]) {
let newEntry = { key: objAfter[key]}
Object.assign(newObj, newEntry)
}
}
console.log(newObj)
The output is:
{ key: 'Johnson' }
I need the output to be:
{ firstName: "John", lastName: "Johnson" }
How do I assign the value of the key (e.g., firstName) instead of the variable (key)?
Just use square brackets on [key]
const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};
let newObj = {};
for(let key in objBefore) {
if (objBefore[key] !== objAfter[key]) {
let newEntry = { [key]: objAfter[key]}
Object.assign(newObj, newEntry)
}
}

How to format an object of objects

I have this object
myObject = {
id: "44",
name: "name",
firstName: "fn",
lastName: "tt",
cars: [],
houses: [],
family: {}
}
I want to format this object to
myObject = {
person: {
id: "44",
name: "name",
firstName: "fn",
lastName: "tt"
},
cars: [],
houses: [],
family: {}
}
Is there anyway i can do this without using delete?
You can use destructuring:
const myObject = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
const { houses, cars, family, ...rest } = myObject
const myNewObject = {
person: rest,
houses,
cars,
family
}
console.log(myNewObject)
You can use destructuring assignments to decompose your object into variables and restructure them in a simple function.
const format = (obj) => {
const {id, name, firstName, lastName, ...props} = obj;
return {person: {id, name, firstName, lastName}, ...props}
}
const formatted = format(myObject);
console.log (formatted)
<script>
var myObject = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
</script>
You could create a new object and assign the properties to it:
let obj = { id:"44", name:"name", firstName:"fn", lastName:"tt", cars: [], houses:[], family:{}}
//I want to format this object to
//myObject = { person: {id:"44", name:"name", firstName:"fn", lastName:"tt"}, cars: [], houses:[], family:{}}
let res = {}
res.person = {id: obj.id, name: obj.name, firstName: obj.firstName, lastName: obj.lastName}
res.cars = obj.cars
res.houses = obj.houses
res.family = obj.family
console.log(res)
You can destructure what you need, put the rest into a variable rest, and then re-assign myObject:
let myObject = {
id: "44",
name: "name",
firstName: "fn",
lastName: "tt",
cars: [],
houses: [],
family: {}
}
const {id, name, firstName, lastName, ...rest } = myObject;
myObject = {
person: { id, name, firstName, lastName },
...rest
}
console.log(myObject);

How to merge an array of objects keep only properties in the first array

I have a working function that merges two arrays of objects by property a1 and a1. The solution was based on answers to some similar questions, however my requirement is to keep only the properties in the original array a1.
How can I adjust this function to return an array of objects containing only the properties in the first array?
Here is a JS fiddle with example data. Note that the output is logged to the console. Also note that the solution must be in vanilla Javascript ES6.
https://jsfiddle.net/dba9r3sf/
const a1 = [
{
FirstName: "John",
LastName: "Doe",
Age: 33,
Username: "jdoe"
},
{
FirstName: "Mary",
LastName: "Bloom",
Age: 63,
Username: "mbloom"
},
{
FirstName: "Alex",
LastName: "Arias",
Age: 21,
Username: "aarias"
}
];
const a2 = [
{
FirstName: "Johnathan",
LastName: "Doe",
Age: 34,
Username: "jdoe",
Job: "Graphic Designer"
},
{
FirstName: "Mary-Anne",
LastName: "Bloom",
Age: 64,
Username: "mbloom",
Job: "Investor"
},
{
FirstName: "Alex",
LastName: "Arias",
Age: 22,
Username: "aarias",
Job: "Student"
}
];
/**
* Merge an array of objects by property
* #param {array} a1 array 1 destination to be merged into
* #param {array} a2 array 2 source to be merged, overwrites existing values in a1
* #param {string} prop name of property to match for merge
* TODO: Set properties that exist on a1 only otherwise ignore
*/
function mergeByProperty(a1, a2, prop) {
let merged = [];
for (let i = 0; i < a1.length; i++) {
merged.push({
...a1[i],
...(a2.find((itmInner) => itmInner[prop] === a1[i][prop]))
});
}
return merged;
}
let result = mergeByProperty(a1, a2, 'Username');
console.log(JSON.stringify(result));
// Output:
[{"FirstName":"Johnathan","LastName":"Doe","Age":34,"Username":"jdoe","Job":"Graphic Designer"},{"FirstName":"Mary-Anne","LastName":"Bloom","Age":64,"Username":"mbloom","Job":"Investor"},{"FirstName":"Alex","LastName":"Arias","Age":22,"Username":"aarias","Job":"Student"}]
// Desired output (no "Job" property because that does not exist in the first array of objects):
[{"FirstName":"Johnathan","LastName":"Doe","Age":34,"Username":"jdoe"},{"FirstName":"Mary-Anne","LastName":"Bloom","Age":64,"Username":"mbloom},{"FirstName":"Alex","LastName":"Arias","Age":22,"Username":"aarias"}]
You can take keys form first array and then select corresponding key/value pair form second array
const a1 = [{FirstName: "John",LastName: "Doe",Age: 33,Username: "jdoe"},{FirstName: "Mary",LastName: "Bloom",Age: 63,Username: "mbloom"},{FirstName: "Alex",LastName: "Arias",Age: 21,Username: "aarias"}];
const a2 = [{FirstName: "Johnathan",LastName: "Doe",Age: 34,Username: "jdoe",Job: "Graphic Designer"},{FirstName: "Mary-Anne",LastName: "Bloom",Age: 64,Username: "mbloom",Job: "Investor"},{FirstName: "Alex",LastName: "Arias",Age: 22,Username: "aarias",Job: "Student"}];
function mergeByProperty(a1, a2, prop) {
let merged = [];
for (let i = 0; i < a1.length; i++) {
let found = a2.find((itmInner) => itmInner[prop] === a1[i][prop])
if(found){
found = Object.keys(a1[0]).reduce((op,inp)=>{
op[inp] = found[inp]
return op
},{})
}
merged.push({
...a1[i],
...found
});
}
return merged;
}
let result = mergeByProperty(a1, a2, 'Username');
console.log((result));
You can create a username map from a2 then simply Array.map over the a1 array and merge with a custom merge function which does nothing more than Array.reduce over the keys of a1 and assigns the values from a2:
const a1 = [ { FirstName: "John", LastName: "Doe", Age: 33, Username: "jdoe" }, { FirstName: "Mary", LastName: "Bloom", Age: 63, Username: "mbloom" }, { FirstName: "Alex", LastName: "Arias", Age: 21, Username: "aarias" } ];
const a2 = [ { FirstName: "Johnathan", LastName: "Doe", Age: 34, Username: "jdoe", Job: "Graphic Designer" }, { FirstName: "Mary-Anne", LastName: "Bloom", Age: 64, Username: "mbloom", Job: "Investor" }, { FirstName: "Alex", LastName: "Arias", Age: 22, Username: "aarias", Job: "Student" } ];
let obj = a2.reduce((r,c) => (r[c.Username] = c, r), {}) // username map
let merge = (a, b, props) => props.reduce((r,c) => (r[c] = b[c], r), a)
let result = a1.map(x => merge(x, obj[x.Username], Object.keys(x)))
console.log(result)
You can do something like this:
const a1 = [
{
FirstName: "John",
LastName: "Doe",
Age: 33,
Username: "jdoe"
},
{
FirstName: "Mary",
LastName: "Bloom",
Age: 63,
Username: "mbloom"
},
{
FirstName: "Alex",
LastName: "Arias",
Age: 21,
Username: "aarias"
}
];
const a2 = [
{
FirstName: "Johnathan",
LastName: "Doe",
Age: 34,
Username: "jdoe",
Job: "Graphic Designer"
},
{
FirstName: "Mary-Anne",
LastName: "Bloom",
Age: 64,
Username: "mbloom",
Job: "Investor"
},
{
FirstName: "Alex",
LastName: "Arias",
Age: 22,
Username: "aarias",
Job: "Student"
}
];
const result = a1.map((obj1, index) => {
const obj2 = a2[index];
if (obj2) {
return Object.keys(obj1).reduce((acc, key) => {
acc[key] = obj2[key];
return acc;
}, {});
}
return obj1;
}, []);
console.log(result);

Convert array of objects with same property to one object with array values

let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
console.log(data)
I want to transform this into one object like this
obj = {firstName: ['John', 'Mike'], lastName: ['Doe', 'Smith']}
should I use reduce?
A generic solution with Array#reduce method.
let result = data.reduce((obj, o) => {
// get all keys of object
Object.keys(o)
// iterate over the keys
.forEach(k => {
// define property if not defined
obj[k] = obj[k] || [];
// push the value to the array
obj[k].push(o[k]);
})
// return object
return obj;
// set initial value as an object for result
}, {})
let data = [{
firstName: 'John',
lastName: 'Doe'
},
{
firstName: 'Mike',
lastName: 'Smith'
}
]
let result = data.reduce((obj, o) => {
Object.keys(o)
.forEach(k => {
obj[k] = obj[k] || [];
obj[k].push(o[k]);
})
return obj;
}, {})
console.log(result)
You can use reduce to create a new version of the object.
The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.
With reduce, we first pass in a function that executes on each item and returns a new output value, then we pass a second parameter defining the initial structure of the single output value.
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
// o = the current output value
// i = the current item in the array
let result = data.reduce((o, i) => {
// Add the first/last names to the corresponding array
o.firstName.push(i.firstName)
o.lastName.push(i.lastName)
// Return the new current output value
return o
}, { firstName: [], lastName: [] }) // Sets the initial output value
console.log(result)
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
var firstName = [];var lastName = [];
data.forEach(function(item){
firstName.push(item.firstName);
lastName.push(item.lastName);
})
let obj = {};
obj.firstName = firstName;
obj.lastName = lastName;
let dataModified = [];
dataModified.push(obj);
console.log(dataModified);
You can also make the logic more generic, irrespective of the properties known
let data = [{
firstName: 'John',
lastName: 'Doe'
},
{
firstName: 'Mike',
lastName: 'Smith'
}
]
let result = data.reduce((o, i) => {
for (const key in i) {
if (!o[key]) {
o[key] = [];
}
o[key].push(i[key]);
}
return o
}, {})
console.log(result)
Another simple thing we can do is to call map two times, once on the first names, and once on the last names.
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
let result = {
firstName: data.map(i => i.firstName),
lastName: data.map(i => i.lastName)
}
console.log(result)
Here's a single iteration, functional, non-mutating solution:
let data = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Mike', lastName: 'Smith'}
]
let result = data.reduce((res, {firstName, lastName}) => ({
firstName: [firstName, ...res.firstName],
lastName: [lastName, ...res.lastName]
}), {firstName: [], lastName: []})
console.log(result)

Categories

Resources