combine two json arrays in javascript - javascript

I have two json arrays like,
array1 = [{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"}]
and
array2 = [{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
I have to combine these two arrays into one array like,
resultarray = [{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"},{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
Please help me.

array1 = [{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"}]
array2 = [{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
console.log(array1.concat(array2));

You can do this using Es 6 new feature:
array1=[{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"}]
array2 = [{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
var combineJsonArray = [...array1, ...array2 ];
//output should be like this [ {"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"},
{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
Or You can put extra string or anything between two JSON array:
var array3= [...array1,"test", ...array2];
// output should be like this : [ {"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"},"test",
{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]

Use the concat function.
var resultarray = array1.concat(array2);
Result shown below:
array1 = [{
"quantity": "5",
"detailed_product_id": "1015",
"detailed_category_id": "9"
}];
array2 = [{
"quantity": "2",
"detailed_product_id": "1003",
"detailed_category_id": "9"
}];
console.log(array1.concat(array2));

Try array.concat for this.
<!DOCTYPE html>
<html>
<head>
<script>
var json1 = [{
"quantity": "5",
"detailed_product_id": "1015",
"detailed_category_id": "9"
}];
var json2 = [{
"quantity": "2",
"detailed_product_id": "1003",
"detailed_category_id": "9"
}]
var json3 = json2.concat(json1);
console.log(json3)
</script>
</head>
</html>

Related

How to scraping JSON that contains a specific string In Javascript with Xpath

I have a HTML data like this.
<script type="application/ld+json">{ "name": "apple", "price": 100 }</script>
<script type="application/ld+json">{ "name": "banana", "price": 200 }</script>
<script type="application/ld+json">{ "name": "orange", "price": 300 }</script>
How can I scrape Json data which contains "banana" with Xpath.
For example, the javascript code below can scrape JSON containing banana. But it's just scraping only the second JSON.
const htmlString = res;
const doc = new DOMParser();
const string = doc.parseFromString(htmlString, 'text/html');
const result = string.evaluate('//script[#type="application/ld+json"]', string, null, 6, null);
const character = result.snapshotItem(2);
console.log(character);
In the code below, the variable is Null.
const htmlString = res;
const doc = new DOMParser();
const string = doc.parseFromString(htmlString, 'text/html');
const result = string.evaluate('//script[contains(text(), "banana")]', string, null, 6, null);
const character = result.snapshotItem(1);
console.log(character);
The image of the goal is { "name": "banana", "price": 200 } .
The index should be 0, since you are targeting exactly which one you want.
const character = result.snapshotItem(0);
Why xpath?
const obj = [...document.querySelectorAll("script[type='application/ld+json']")]
.map(script => JSON.parse(script.textContent))
.filter((item)=>item.name==="banana")
console.log(obj[0])
<script type="application/ld+json">{ "name": "apple", "price": 100 }</script>
<script type="application/ld+json">{ "name": "banana", "price": 200 }</script>
<script type="application/ld+json">{ "name": "orange", "price": 300 }</script>
You can also get there with:
result = string.evaluate('//script[contains(text(), "banana")]/text()', string, null, 6, null),
character = result.snapshotItem(0).nodeValue;
console.log(character);

Convert a one dimensional array into an array of objects with Javascript

I've flattened an array like this: let playerPool = [...new Set(array.flat(1))];
Which has an output like this: ["Howard Bell", "Matt Blair", "Dave Custer"]
How can I turn this into an array of objects? I want to update the above so the format is like this:
[ {Name: "Howard Bell", Count: "0"}, {Name: "Matt Blair", Count: "0"}, {Name: "Dave Custer", Count: "0"} ]
I was trying to set this up by looping through the playerPool array but I get the following error: TypeError: Cannot set property 'Name' of undefined
let playerPool = [...new Set(array.flat(1))];
let playerObjects = [];
for(let i = 0; i < playerPool.length; i++) {
playerObjects[i].Name = playerPool[i];
playerObjects[i].Count = 0;
}
My goal is to be able to reference each property individually like this playerObjects[0].Count so I can later update the count value.
You forgot to create the object to which you want to assign the properties.
But you can do it more functional-style with map:
let playerPool = ["Howard Bell", "Matt Blair", "Dave Custer"];
let result = playerPool.map(name => ({name, count:0}));
console.log(result);
NB: if possible choose camelCase for your property names. There is a common practice to reserve PascalCase for constructor names ("classes").
You can try something like this,
let array1 = ["Howard Bell", "Matt Blair", "Dave Custer"];
let array2 = [];
array1.forEach(el => {
array2.push({Name: el, count: 0});
});
console.log(array2);

Remove specific properties from Array objects in Node.js

For example I have this array, if I stringfy it it would be like this:
[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
How can I do for remove from the 2 cars: the doors and price. And only leave in the array "car" and "id"? For example:
[{"car":"Toyota","ID":"1"},{"car":"Chevrolet","ID":"2"}]
Thank you!
let arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
let arr1 = arr.map(({car, ID}) => ({car, ID}));
let arr2 = arr.map(({Doors, price, ...remainingAttrs}) => remainingAttrs);
console.log('arr1:', arr1);
console.log('arr2:', arr2);
With ES6 syntax, you can deconstruct each object to create new one without writing a loop.
In your case, total number of fields remaining is same as the total number of deleted
Following are the two approaches:
If less number of fields are to be preserved, then you can go with:
const arr1 = arr.map(({car, ID}) => ({car, ID}))
If less number of fields are to be removed, then you can go with:
const arr2 = arr.map(({Doors, price, ...remainingAttrs}) =>
remainingAttrs)
You can use Array.prototype.map() to customise your result array, taking a callback function as parameter which returns a new customised object, having only car and ID properties, in each iteration.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
This is how should be your code:
var results = arr.map(function(item){
return {car : item["car"], ID : item["ID"]}
});
Demo:
var arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var results = arr.map(function(item){
return {car : item["car"], ID : item["ID"]}
});
console.log(JSON.stringify(results));
Adding to all other answers
Cleaner approach using ES6 syntax
var originalArray =[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var immutableArray = originalArray.map(({Doors, price, ...rest})=> rest);
console.log(immutableArray);
You must iterate over your array deleting the property on each object.
Example:
for (var i = 0; i < myArray.length; i++){
delete myArray[i].myProperty
}
Adding to the answers, with ES6 and to avoid mutation and some ESlint issues.
const Array = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},
{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
const newArray = Array.map((object) => {
const {car, ID} = object;
return {car, ID};
});
Check comment for explanation:
var array=[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var resultArr = array.map(function(obj){
//we take only key-value pairs we need using JS bracket notation
return {"car":obj["car"],"ID":obj["ID"]};
});
console.log(resultArr);
You would be looking for the delete operator to fully remove those properties. It could look something like this:
var array = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
for (car of array) {
delete(car.Doors);
delete(car.price);
}
You could also look into using Array.splice() for faster performance on large arrays.

Javascript create array with fixed value but matching column amount from another array

I have an array which is built from data dynamically, so it can change.
It's basically this:
["t1", "something", "bird", "dog", "cow", "fish"]
What I need to do is to count how many of them there are and create another array with the same amount of columns but all with the value of 1.
For example, if the array is:
["bird", "dog", "cow", "fish"]
then it creates an array of:
[1, 1, 1, 1]
If the array is:
["bird", "fish"]
then it creates an array of:
[1, 1]
How can I do this?
You can use the Array.prototype.map method:
var input = ["foo", "bar", "baz"];
var mapped = input.map(function () { return 1; });
Just create a new array of equal length and use the fill function.
var myArray = ["dog","cat","monkey"];
var secondArray = new Array(myArray.length).fill(1);
// es6
var array = ["t1", "something", "bird", "dog", "cow", "fish"]
array.map(() => 1); // => [1, 1, 1, 1, 1, 1]
// if you don't care if they are strings
'1'.repeat(array.length).split(''); //=> ["1", "1", "1", "1", "1", "1"]

Merge Arrays Combining Matching Objects in Angular Javascript

I have 2 array objects in Angular JS that I wish to merge (overlap/combine) the matching ones.
For example, the Array 1 is like this:
[
{"id":1,"name":"Adam"},
{"id":2,"name":"Smith"},
{"id":3,"name":"Eve"},
{"id":4,"name":"Gary"},
]
Array 2 is like this:
[
{"id":1,"name":"Adam", "checked":true},
{"id":3,"name":"Eve", "checked":true},
]
I want the resulting array after merging to become this:
[
{"id":1,"name":"Adam", "checked":true},
{"id":2,"name":"Smith"},
{"id":3,"name":"Eve", "checked":true},
{"id":4,"name":"Gary"},
]
Is that possible? I have tried angular's array_merge and array_extend like this:
angular.merge([], $scope.array1, $scope.array2);
angular.extend([], $scope.array1, $scope.array2);
But the above method overlap the first 2 objects in array and doesn't merge them based on matching data. Is having a foreach loop the only solution for this?
Can someone guide me here please?
Not sure if this find of merge is supported by AngularJS. I've made a snippet which does exactly the same:
function merge(array1, array2) {
var ids = [];
var merge_obj = [];
array1.map(function(ele) {
if (!(ids.indexOf(ele.id) > -1)) {
ids.push(ele.id);
merge_obj.push(ele);
}
});
array2.map(function(ele) {
var index = ids.indexOf(ele.id);
if (!( index > -1)) {
ids.push(ele.id);
merge_obj.push(ele);
}else{
merge_obj[index] = ele;
}
});
console.log(merge_obj);
}
var array1 = [{
"id": 1,
"name": "Adam"
}, {
"id": 2,
"name": "Smith"
}, {
"id": 3,
"name": "Eve"
}, {
"id": 4,
"name": "Gary"
}, ]
var array2 = [{
"id": 1,
"name": "Adam",
"checked": true
}, {
"id": 3,
"name": "Eve",
"checked": true
}, ];
merge(array1, array2);
Genuinely, extend in Angular works with object instead of array. But we can do small trick in your case. Here is another solution.
// a1, a2 is your arrays
// This is to convert array to object with key is id and value is the array item itself
var a1_ = a1.reduce(function(obj, value) {
obj[value.id] = value;
return obj;
}, {});
var a2_ = a2.reduce(function(obj, value) {
obj[value.id] = value;
return obj;
}, {});
// Then use extend with those two converted objects
var result = angular.extend([], a1_, a2_).splice(1)
Notes:
For compatibility, reduce may not work.
The after array will replace the previous one. This is because of implementation of extend in Angular.

Categories