Merge two diffrent json in one json - node.js

I have two json arrays like
var json1 = [{"city":"Ahmedabad"}]
var json2 = [{"State":"Gujarat"}]
I want them merge in to single arrays
var finalObj = [{"city":"Ahmedabad","State":"Gujarat"}]

If you are using concat() method then the arrays will get merged not the elements then you will get an output somewhat like
[{"city":"Ahmedabad"},{"State":"Gujarat"}]
If you need an output like this,
[{"city":"Ahmedabad","State":"Gujarat"}]
then you can implement this,
var json1 = [{"city":"Ahmedabad"}];
var json2 = [{"State":"Gujarat"}];
function jsonConcat(destinationObj, sourceObj) {
for (var key in sourceObj) {
destinationObj[key] = sourceObj[key];
}
return destinationObj;
}
//since json1 & json2 are arrays you must mention index,
//here index is 0, because it's first json object
var finalObj = jsonConcat(json1[0], json2[0])
console.log(finalObj)
IMPORTANT - This function will replace if similar keys found in both arrays !

If two json arrays have the same length, like your example, each json object is a array what includes one object.
You can loop through each item of the json arrays, then merge all of them to a object, finally push it into a array - finalObj.
My way use Object Rest/Spread Properties, the feature available with es2018:
var json1 = [{ "city": "Ahmedabad" }]
var json2 = [{ "State": "Gujarat" }]
var finalObj = [];
for (let i = 0; i < json1.length; i++) {
finalObj.push({
...json1[i],
...json2[i]
})
}
console.log(finalObj);

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var finalObj = json1.concat(json2)

merge your array
use reduce to merge all the items into one object
wrap in array
var combinedObj = [...json1, ...json2].reduce((acc, obj) => {
return {
...acc,
...obj
}
}, {})
var combinedArr = [...combinedObj]

You can do merge by using spread / rest operators i.e ...
var json1 = [{"city":"Ahmedabad"}]
var json2 = [{"State":"Gujarat"}]
var result = [...json1, ...json2]; //this will merge them into one.
result will be new array as we have merge them into one.
You can also user concat method of Javascript. Please refer below for concat -
https://www.w3schools.com/jsref/jsref_concat_array.asp
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_concat

Related

Get Date from Nested Array of Objects and set that date as an Key in Node.js

I'm using Node.js I have data like this:
const data= [
{"id":"1","date":"2022-09-07T15:56:32.279Z","req_id":"98"},
{"id":"2","date":"2022-09-08T15:48:19.075Z","req_id":"97"},
{"id":"3","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
{"id":"4","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
]
I want data in this format:
expected Output:
"2022-09-06":[
{"id":"4","date":"2022-09-06T15:48:19.073Z","req_id":"96"},
{"id":"3","date":"2022-09-06T15:48:19.073Z","req_id":"96"}
]
"2022-09-08":[
{"id":"2","date":"2022-09-08T15:48:19.075Z","req_id":"97"}
]
"2022-09-07":[
{"id":"1","date":"2022-09-07T15:56:32.279Z","req_id":"98"}
]
Assuming the dates are always in the same format, I would do something like this:
function mapData(data){
// returns the given date as an string in the "%dd-%mm-%yyyy" format
const getDateWithoutTime = (dateString) => dateString.split("T")[0];
const mappedData = [];
for(const req of data){
const formattedDate = getDateWithoutTime(req.date);
// if the key already exists in the array, we add a new item
if(mappedData[formattedDate]) mappedData[formattedDate].push(req);
// if the key doesn't exist, we create an array with that single item for that key
else mappedData[formattedDate] = [req];
}
return mappedData;
}
Straightforward solution using regex:
let result = new Map();
for (const item of data) {
let date = item['date'].match(/\d{4}-\d{2}-\d{2}/)[0];
let items = result.get(date) || [];
items.push(item);
result.set(date, items)
}

How do I access content from JSON string?

I am receiving a JSON object from the backend now I just want "result" array only in my template variable in my angular application from it.
{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}
Try with
variable_name["result"].
Try with
var data = response from the backend
var result = data.result;
$var = '{"result":[{"name":"Sunil Sahu","mobile":"1234567890","email":"abc#gmail.com","location":"Mumbai","Age":"19"}],"stats":200}';
If your $var is string, you need to turn it to "array" or "object" by json_decode() function
object:
$var_object = json_decode($var); //this will get an object
$result = $var_object->result; //$result is what you want to get
array:
$var_array = json_decode($var, true); //this will get an array
$result = $var_array['result']; //$result is what you want to get
Else if $var is object, direct use
$result = $var->result; //$result is what you want to get
As result is an array of objects, you can either use any loop to extract key value pair or you can directly access the array using index value.
var results = data["result"] // this would return an array
angular.forEach(results, function(value, key) {
//access key value pair
});
For accessing results in HTML, ng-repeat directive can be used.
Your question didn't explain further, but in the simple way try this :
const stringJson = `{
"result":[
{"name":"Sunil Sahu",
"mobile":"1234567890",
"email":"abc#gmail.com",
"location":"Mumbai",
"Age":"19"
}
],
"status":200
}`
const obJson = JSON.parse(stringJson);
console.log(obJson.result);

Using GEE code editor to create unique values list from existing list pulled from feature

I'm working in the Google Earth Engine code editor. I have a feature collection containing fires in multiple states and need to generate a unique list of states that will be used in a selection widget. I'm trying to write a function that takes the list of state values for all fires, creates a new list, and then adds new state values to the new unique list. I have run the code below and am not getting any error messages, but the output is still statesUnique = []. Can anyone point me in the right direction to get the new list to populate with unique values for states?
My Code:
// List of state property value for each fire
var states = fire_perim.toList(fire_perim.size()).map(function(f) {
return ee.Feature(f).get('STATE');
}).sort();
print('States: ', states);
// Create unique list function
var uniqueList = function(list) {
var newList = []
var len = list.length;
for (var i = 0; i < len; i++) {
var j = newList.contains(list[i]);
if (j === false) {
newList.add(list[i])
}
}
return newList
};
// List of unique states
var statesUnique = uniqueList(states);
print('States short list: ', statesUnique)
Okay, I did not come up with this answer, some folks at work helped me, but I wanted to post the answer so here is one solution:
var state_field = 'STATE'
var all_text = 'All states'
// Function to build states list
var build_select = function(feature_collection, field_name, all_text) {
var field_list = ee.Dictionary(feature_collection.aggregate_histogram(field_name))
.keys().insert(0, all_text);
return field_list.map(function(name) {
return ee.Dictionary({'label': name, 'value': name})
}).getInfo();
};
var states_list = build_select(fire_perim, state_field, all_text)
print(states_list)

Concurrently iterate over two iterables of same length

I have two iterables of the same length that I need to loop over at the same time. One iterable is a Map of custom objects, and the other is an array of objects. I need to add the contents of the array into the Map (via some helper prototype functions), preferably asynchronously and concurrently. Also, the two containers are associated to each other based on their order. So the first element in the array needs to be added to the first element in the Map.
If I was to do this synchronously it would look something like this:
var map;
var arr;
for (var i = 0; i < arr.length; i++) {
// get our custom object, call its prototype helper function with the values
// in the array.
let customObj = map[i];
customObj.setValues(arr[i])
}
Typically to loop over arrays async and concurrently I use bluebirds Promise.map. It would look something like this:
var arr
Promise.map(arr, (elem) => {
// do whatever I need to do with that element of the array
callAFunction(elem)
})
It would be awesome if I could do something like this:
var map;
var arr;
Promise.map(map, arr, (mapElem, arrElem) {
let customObj = mapElem[1];
customObj.setValue(arrElem);
})
Does anyone know of a library or a clever way to help me accomplish this?
Thanks.
EDIT: Just want to add some clarification on the objects stored in the map. The map is keyed on a unique value, and values are associated with that unique values are what make up this object. It is defined in a similar manner to this:
module.exports = CustomObject;
function CustomObject(options) {
// Initialize CustomObjects variables...
}
CustomObject.prototype.setValue(obj) {
// Logic for adding values to object...
}
if you already know, that the Map (I assume you really mean the JavaScript Map here, which is ordered) and the array have the same length, you do not need a mapping function, that takes both the array AND the map. One of both is enough, because the map function also gives you an index value:
var map;
var arr;
Promise.map(map, (mapElem, index) => {
let customObj = mapElem[1];
customObj.setValue(arr[index]);
});
You can use the function Promise.all that execute all the given asynchronous functions.
You should know that actually node.js support fully Promises, you do not need bluebirds anymore.
Promise.all(arr.map(x => anyAsynchronousFunc(x)))
.then((rets) => {
// Have here all return of the asynchronous functions you did called
// You can construct your array using the result in rets
})
.catch((err) => {
// Handle the error
});

NotesViewEntry sort items

I have following code in the data binding of a data table. I would like to sort the items (viewEntries) on part (spareProductPart) in order to display them sorted in my data table.
var thisDb:NotesDatabase = sessionAsSigner.getDatabase("","demo/demo.nsf");
Ventry=function(ve:NotesViewEntry){
this.prod=entry.getDocument().getItemValueString("spareProduct");
this.drawing=entry.getDocument().getItemValueString("spareDrawingNumber");
this.part=entry.getDocument().getItemValueString("spareProductPart");
this.unid=entry.getUniversalID();
etc ....
}
var viewEntries=[];
var Collection:NotesViewEntryCollection=thisDb.getView("parts").getAllEntries();
Collection.FTSearch(viewScope.toSearch);
var entry:NotesViewEntry=Collection.getFirstEntry();
while (entry!=null){ //loop over all entryes
viewEntries.push( new Ventry( entry) )
entry = Collection.getNextEntry();
}
return (viewEntries);
Use NotesView's FTSearchSorted instead of FTSearch.
Your code would look like this then:
...
var viewEntries = [];
var viewParts:NotesView = thisDb.getView("parts");
viewParts.FTSearchSorted(viewScope.toSearch, 0, "yourSortedColumnName");
var Collection:NotesViewEntryCollection = viewParts.getAllEntries();
var entry:NotesViewEntry = Collection.getFirstEntry();
...
"This class provides you mainly with a collection of documents in a view-sorted order." That means if you want your viewEntryCollection sorted by the part number, your view would have to be sorted that way. So the answer: change the view so that it's sorted by by spareProductPart

Resources