Merge Array of Objects - javascript

I need to merge arrays of objects in browserside javascript like this:
[
{name: "john", age: 10},
{name: "doe", age: 14}
]
--> new data arrives
[
{name: "pete", age: 88},
{name: "larry", age: 42}
]
should become
[
{name: "john", age: 10},
{name: "doe", age: 14},
{name: "pete", age: 88},
{name: "larry", age: 42}
]
Well thats simplified the arrays will contain hundreds of larger objects. Therefore I need a performant solution.
Thanks in advance yours skeec

It seems you can just use .push() or .concat() to combine the two arrays. It does not matter what is in the arrays as the array operators just work on the elements of the array abstractly without knowing what's in them.
Here's a solution that adds the new array onto the existing one:
var data = [
{name: "john", age: 10},
{name: "doe", age: 14}
];
var newInfo = [
{name: "pete", age: 88},
{name: "larry", age: 42}
]
data = data.concat(newInfo);
Or, if you really want to keep the original array (not create a new one), you can add the new array onto the end of the original array like this:
data.push.apply(data, newInfo);

Assuming you don't need anything other than just concatenating the 2 arrays, it's supremely simple, since arrays have a method for concatenation already.
var arr1 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var arr2 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var concatArr = arr1.concat(arr2);
MDN Page on Array.prototype.concat

var arr3 = [];
for(var i in arr1){
var shared = false;
for (var j in arr2)
if (arr2[j].name == arr1[i].name) {
shared = true;
break;
}
if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);

You can use loadash for that:
Something like this:
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// → [1, 2, 3, [4]]
console.log(array);
// → [1]
Or for Json you can use extend like this:
lodash.extend({}, mergeInto, toMerge)

Related

How to rearrange different type of associative array in Typescript?

I want to rearrange to different type of associative array to extract same property.
So I tried to make sample code below.
const array1 = [{name:'john',age:25},{name:'Bob',age:33}];
const array2 = [{name:'Jen',age:35,id:1},{name:'Mera',age:31,id:2}];
const array3 = array1.concat(array2);
console.log(array3)
and this code reuld is like that.
0: {name: "john", age: 25}
1: {name: "Bob", age: 33}
2: {name: "Jen", age: 35,id:1}
3: {name: "Mera", age: 31,id:2}
my goal is just below.
0: {name: "john"}
1: {name: "Bob"}
2: {name: "Jen"}
3: {name: "Mera"}
Could someone adivise me, please?
If you just want the values to have a name property, then you should just map() the array elements to ones with just a name property. For example:
const array3 = [...array1, ...array2].map(({ name }) => ({ name }));
console.log(array3);
// [ { "name": "john" }, { "name": "Bob" }, { "name": "Jen" }, { "name": "Mera" } ]
Here I'm using spread in array literals instead of concat(), and destructuring assignment for the object mapping. If those are weird looking, you could rewrite it as:
const array4 = array1.concat(array2).map(value => ({ name: value.name }));
which does pretty much the same thing. Hope that helps; good luck!
Playground link

How can I convert an array of objects into an array of objects with the same values but with modified keys?

I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)
For example, an array of
[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]
becomes
[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Using the Map function works perfectly here.
const people = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
const formatted = people.map((person) => ({
identification: person.name,
years: person.age,
person: person.person
});
This should work for this problem.
I think that you may use the map method this method returns and array with the same length as the one you are mapping:
const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];
let newKeysArray = array.map( a => {
let obj = {
identification: person.name,
years: person.age,
person: person.person
};
return obj
} );
So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.
Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:
let rows = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
let keyMaps = [
['name', 'identification'],
['age', 'years'],
];
for(let keyMap of keyMaps)
for(let row of rows)
delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];
console.log(rows);
keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.

Check if same object exists in an array - Javascript

I have an array of objects as follows
[{name: "jack", age: 10}, {name: "john", age: 15}]
Consider that i have an object
{name: "jack", age: 10}
Now i need to check if this object exist in the array. If all the properties(name, age) of the object matches, then display an alert on the page.
How to accomplish this using pure javascript?
Use Array.some, Array.every and Object.entries
A match will be counted if
There are equal number of keys
There is a match for every key/value pair
var arr = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
var result = arr.some((o) => Object.entries(input).every(([k,v]) => o[k] === v) && Object.keys(input).length === Object.keys(o).length);
console.log(result);
Try this:
var data = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
for(var i=0;i<data.length;i++)
{
if(data[i].name==input.name && data[i].age == input.age)
{
alert('matched');
break;
}
}
This may be a bad performing method, but it would cover nested object cases with ease. Also this is only suited if ALL key/value pairs must match and that the key/value pairs were defined in the same order.
let c = [{name: "jack", age: 10}, {name: "john", age: 15}],
s = {name: "jack", age: 10};
console.log(c.filter(e => JSON.stringify(s) === JSON.stringify(e)));
You can try this if you don't want to check for index of object inside array object
var obj = [{name: "jack", age: 10}, {name: "john", age: 15}];
var checkObj = {name: "john", age: 15};
if(JSON.stringify(obj).indexOf(JSON.stringify(checkObj)) >= 0){
console.log("Object Available");
}else{
console.log("Object Not Available");
}

ES6 Object Spread concat

I am new to object spread. I just knew object spread can be used to concat arrays . In below example i am concatenating variable a and address key. I want to know can we add address key value to each object of a array and get output as Required Output in code.
Can any one help me good reference to learn more on Object Spread.
var a = [{
'name':'jay',
age: 31
},
{
'name':'jay1',
age: 30
},
{
'name':'jay2',
age: 29
}];
var b = {...a, ...{address: 'add'}};
//b output
{name: "jay", age: 31}
{name: "jay1", age: 30}
{name: "jay2", age: 29}
address:"add"
// Required Output
{name: "jay", age: 31, address:"add"}
{name: "jay1", age: 30, address:"add"}
{name: "jay2", age: 29, address:"add"}
{ value:1, ...a, ...b, value:3 }
equals:
Object.assign({value:1}, a, b, {value:3})
In your case you need to do that for every element of your array:
const result = a.map(obj => ({...obj, address:"add"}));

Access object property values in an array of objects javascript

I have an array containing objects that looks like this:
var persArr = [
{name: "Adam", age: 37},
{name: "Ben", age: 36},
{name: "Chris", age: 46}
];
What I would like to do is create a string variable which takes the given names in each object in the array and puts them together like this:
var str = "Adam, Ben, Chris";
Any suggestions as to achieve this?
You can use map and join:
var str = persArr.map(function (pers) {
return pers.name;
}).join(", ");
Try with:
var names = [];
for (var k in persArr) {
names.push(persArr[k].name);
}
var str = names.join(', ');
try something like this
var persArr = [{name: "Adam", age: 37}, {name: "Ben", age: 36}, {name: "Chris", age: 46}];
var ar_length = persArr.length;
var temp_arr = [];
for(var i= 0;i<ar_length;i++){
temp_arr.push(persArr[i].name);
}
alert(temp_arr.join(','));

Categories

Resources