Merge Two json array in one in Node Js - javascript

I have two json arrays like
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{sec:'A', class_name:'xyz' ...}]
I want them merge in to single arrays
var finalObj = [{id:1, name: 'xxx' ...},{id:sec, name: class_name ...},{id:A, name: 'xyz' ...}... ]

If both objects have a property with the same name, then the second object property overwrites the first. The best solution in this case is to use Lodash and its merge() method, which will perform a deeper merge, recursively merging object properties and arrays.

Try this to concatinate two arrays into one.
var finalObj = json1.concat(json2);

I am not sure if I get this right as you have the properties of second array as values in the expected result, but if you want to merge both arrays you could use spread operator:
var finalObj = [...json1, ...json2]

Related

array.map() : Return array instead of object (JavaScript)

I'm still a newbie with javascript. I'm facing a problem with mapping an array. I don't know how to return the an array with objects.
This is the initial array:
array1 = [{firstName: "Harry"},
{lastName: "Potter"}];
When i do array1.map, it returns:
array1 = ["Potter"];
I want to make array1 to be like this after mapping the lastName:
array1 = [{lastName: "Potter"}];
You can use filter function instead
array1 = [{firstName: "Harry"},
{lastName: "Potter"}];
console.log(array1.filter(x => x.lastName === "Potter"));
As per the docs:
The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.
It creates new array and returns it.

How to check if array contains objects

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

Proper way to add an object to an array using concat

var obj = {name: 'tim', bio: 'lol'};
var arr = [{name: 'beba', bio:'lulu'}, {name: 'keh', bio: 'kih'}];
var newArr = arr.concat([obj]);
or
var newArr = arr.concat(obj);
Both concats work but one is with square brackets and the other without them. Are they both correct?
If you look at the docs of concat
Yes it is fine. concat function is flexible enough.
The concat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). It does not recurse into nested array arguments.
It internally checks what you are passing and do the things.
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
Update :
var newArr = arr.concat(obj);
Means you are passing a single object to concat function.
var newArr = arr.concat([obj]);
Means you are passing an array with being a single object in it.
Basically [] denotes an array.

JQuery string to Object Array

I call the function tabulator() with these params.
$("#tableObj").tabulator("addRow", {id:1, Name:"John", Age:"20"}, true);
I want to pass the Array elements name dynamically,
read from a Json ( '{id:1, Name:"John", Age:"20"}' ).
I mean that column names will change.
Ex : {id:1, Company:"myComp", Address:"myaddress"}
How can I create theses objs from Strings or JSon text?
You could use JSON.parse but be aware that id:1, Name:"John", Age:"20" is NOT valid JSON. The keys must be wrapped in quotes, otherwise it will produce an error.
var str = '{"id":1, "Name":"John", "Age":"20"}';
var obj = JSON.parse(str);
$("#tableObj").tabulator("addRow", obj, true);

Which JS methods/libs to extract selected arrays and properties from a complex object

Let's say I have an array of JSON objects such as below:
{
title: 'foo',
alias: 'bam',
innerArr: [{
name:'foo',
id:'123',
options: [{id:3,title:'boo',values:[{id:5,name:'Boo'}] }]
}]
}
Is there any library or shorthand method that doesn't involve writing nested for loops that will iterate over a collection of such objects and create a new array, but only with the properties I want projected/selected. So, say I want a copy of this array, but don't want the property title and the nested options[{}] array in the target array. So this new array will have all the same data, but each member of the array will now not have those two objects. Something I can overload like so perhaps var newarr = method({}, sourceArray, {title, options });
Just create a clone object (or you could work on initial object) and delete what you want, e.g:
var newObj = JSON.parse(JSON.stringify(o));
delete newObj.title;
newObj.innerArr.forEach(function(_o, i){delete _o.options});
console.log(newObj);
If you have to deal with specific nested objects as Date, use jQuery extend to clone object.
var newObj = $.extend({}, oldObject);
Let's say I have an array of JSON objects
For an array of object:
var newArr = JSON.parse(JSON.stringify(arr));
newArr.forEach(function (_o, i) {
delete _o.title;
_o.innerArr.forEach(function (__o, i) {
delete __o.options
});
});
console.log(newArr);
-jsFiddle-
EDIT: now i guess some library as prototypejs would have some handful methods but i don't know this library.

Categories

Resources