How do I get the sum of two json objects? - reactjs

This is the json data I have. I need the sum of 'homescorepoints' + 'homeframepointsadj' and/or
'awayscorepoints' + 'awayframepointsadj'...
"512830": {
"compname": "VNEA Vegas League",
"grade": "",
"hometeamlabel": "Pool Tang Clan",
"homeshortlabel": "Pool Tang Clan",
"awayteamlabel": "All Shades",
"awayshortlabel": "All Shades",
"homescore": 11,
"homescorepoints": "187",
"homeframepointsadj": "5",
"awayscore": 14,
"awayscorepoints": "178",
"awayframepointsadj": "0",
}
I understand the basic array. Reduce for adding multiple occurrences of say "awayscore", but I'm have a mental block with adding two separate objects values together.

Assuming that you wanted to sum values from this example object: .reduce() accept arrays so, you can use Object.values() method for your object to get the array and than use .reduce() like this:
const jsonData = {
"512830": {
"compname": "VNEA Vegas League",
"grade": "",
"hometeamlabel": "Pool Tang Clan",
"homeshortlabel": "Pool Tang Clan",
"awayteamlabel": "All Shades",
"awayshortlabel": "All Shades",
"homescore": 11,
"homescorepoints": "187",
"homeframepointsadj": "5",
"awayscore": 14,
"awayscorepoints": "178",
"awayframepointsadj": "0",
}
};
const calculateScore = (data, type) =>
Object.values(data).reduce((acc, curr) =>
acc + parseInt(curr[`${type}scorepoints`]) + parseInt(curr[`${type}framepointsadj`]), 0);
const homeScore = calculateScore(jsonData, 'home');
const awayScore = calculateScore(jsonData, 'away');
console.log(homeScore);
console.log(awayScore);

Related

Calculation on dynamic data in React

This array can be fetched by .map in return()
[
{
"a": "3",
"Count": "3",
"b": "299.98999786376953",
"c": "30",
"d": "30"
},
{
"a": "9",
"Count": "1",
"b": "99.98999786376953",
"c": "10",
"d": "9"
}
]
I want to apply formulas on it like:
a = a/Count;
b = (b/(Count*10))*100;
c = (c/(Count*10))*100;
d = (d/(Count*10))*100;
Also find e = (a+b+c+d)/4;
then display them in each table row's data using .map
I tried npmjs.com/package/react-equation, it can do calculations directly in return() however don't fetch dynamic variables of array inside return(). I also tried creating a function outside return add(a,b){return a+b) and calling it inside return(), neither do it work and tried some other methods as well.
Here is a sample code that can help you continue your work. It uses map to transform your string array to float array and also return the new calculated objects
const array = [
{
"a": "3",
"Count": "3",
"b": "299.98999786376953",
"c": "30",
"d": "30"
},
{
"a": "9",
"Count": "1",
"b": "99.98999786376953",
"c": "10",
"d": "9"
}
]
const newArray = array.map(obj => {
const a = parseFloat(obj.a) / parseFloat(obj.Count);
const b = (parseFloat(obj.b)/(parseFloat(obj.Count) * 10)) * 100
const c = (parseFloat(obj.c)/(parseFloat(obj.Count) * 10)) * 100
const d = (parseFloat(obj.d)/(parseFloat(obj.Count) * 10)) * 100
return { a, b, c, d, e: (a+b+c+d)/4}
})
console.log(array, newArray)
I don't think you can really use map because you're doing different calculations for a and for b,c,d and for e, and also because the calcultions on a depends on value of Count. You could just define a function that accepts the entire object and performs the calculations like so:
const performCalculations = (obj) => {
obj.a = obj.a / obj.Count;
obj.b = (obj.b/(obj.Count*10))*100;
obj.c = (obj.c/(obj.Count*10))*100;
obj.d = (obj.d/(obj.Count*10))*100;
obj.e = (obj.a + obj.b + obj.c + obj.d)/4;
return obj;
}
Edit: you can use map see #Apostolos answer

How can i merge two array data in react native?

i want fetch 2 data and push array, then merge this two data, who can help me?
My first data example;
{
"experts": [
{
"id": 1,
"name": "XXXXX",
"integration_id": "1",
},
{
"id": 243,
"name": "YYYY",
"integration_id": "2",
},] }
My Second data example https://xxx/api/?staff={integration_id}
{
"uzmanlar": [
{
"id": "1",
"ad_soyad": "xxx",
"pic": "117-k-xxx.jpg",
}
],
}
i want foreach first data array to second data merge. i want print picture screen
const arr1 = res.exprts;
const arr2 = res.uzmanlar;
Array.prototype.push.apply(arr1, arr2);
console.log(arr1) // final merge result would be in arr1
you can try this...
You can achieve this using the ... Spread Syntax:
const array = [...obj1["experts"], ...obj1["uzmanlar"]]
This creates a new array including all elements of the first and second array.

How to pass a column with single row which consists of nested array in Spark Scala?

I need to work with this json structure;
val sample_data = """{
"Record": {
"Id": "id",
"IdsArray": [{
"Id1": 1234,
"Id2": "master_id",
"Id3": "11",
"Id4": "12",
"Id5": "13"
},
{
"Id1": 4321,
"Id2": "master_id",
"Id3": "21",
"Id4": "22",
"Id5": "23"
}],
"NameArray": [{
"Number": 1234567890,
"Date1": "some date",
"Date2": "some another date",
"FirstName": "Ron",
"MiddleName": "",
"LastName": "Swanson",
"NameSuffix": "Mr."
}]
}
}"""
I want to flatten this json and choose one of the array from two arrays that we have in IdsArray. For example, I may want to choose based on Id1 value, i.e. whichever value is larger select that block of array out of all available array elements.
val df = spark.read.json(Seq(sample_data).toDS)
df.select($"Record.*")
.select($"NameArray", $"IdsArray")
.withColumn("someColName", myFuncUDF($"IdsArray")
....
....
This is the general flow of logic I have tried.
For the UDF, I have tried like this;
val myFunc = (col_array: Array[Array[Any]]) => {
<some conditions and logic>
}
val myFuncUDF = udf(myFunc)
When I try to run with this, I get error;
myFunc: Array[Array[Any]] => Any = <function1>
java.lang.UnsupportedOperationException: Schema for type Any is not supported
My question is what is the correct way to pass the parameter to the function. Or, what is the best way to approach for these type of problem? For this particular problem .withColumn("someColName", myFuncUDF($"IdsArray") should give me value in IdsArray[1] because Id1 value in IdsArray[1] is 4321 which is greater than 1234.

Angular2,Typescript:How to push array of objects into another array of objects with only a few fields of the object

I know how to operate on array of objects but never had the necessity to push one array data into another. I need to push an array of objects into another array with only 2 fields of the object. Right now my object format is somewhat like this
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
I want to push this into another array but I want only courseid and name in the object. I've read that we need to initialise the object in the constructor, use slice() and a few other functions and then push but I don't know how can I do it for mine since I need to push one array data into another.Kindly someone help me in this regard.
You're looking for the array map() method:
const newArray = array.map(o => {
return { name: o.name, courseid: o.courseid };
});
Try this:
let data = [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
let other = []; // your other array...
data.map(item => {
return {
courseid: item.courseid,
name: item.name
}
}).forEach(item => other.push(item));
console.log(JSON.stringify(other))
// => [{"courseid":"1","name":"Btech"},{"courseid":"2","name":"BCom"}]
You can simply do it like this.
//assign your array of object to variable
var youArray:Array<any>= [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
var resultArray:Array<any>=[] //empty array which we are going to push our selected items, always define types
youArray.forEach(i=>{
resultArray.push(
{
"name":i.name,
"courseid":i.courseid
});
});
console.log(resultArray)
if you still have doubts about this.please follow this url
Map to a returning JSON data, subscribe it to an existing array or an empty one. #typescript
let pictimeline= [];
var timeline = this.picService.fetchtimeline(this.limit)
.map((data : Response) => data.json())
.subscribe(pictimeline=> this.pictimeline = pictimeline);
console.log(this.pictimeline);

Print JSON array in expected format

This is the code to get the details from my table.
function listshops(callback)
{
var array=[3,4];/*shopId*/
async.each(array,function(dat,callback){
async.parallel([
function(callback){
client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
callback(null,data1);
});
},
function (callback) {
client.connection.query('select * from image where shopId=?',dat,function(err,data2){
callback(null,data2);
});
}
],
function(err,data)
{
var result = data.reduce(function(prev, curr) { /*merging the array*/
return prev.concat(curr);
});
console.log(result);
});
});
}
I got an output like this:: http://i.stack.imgur.com/NVUAu.png
i want to print my result in the below format:
{
"shops": [
{
"shopId": "3",
"shopName": "1",
"address": "abc",
"contactNumber":"1234"
"images": [
{
"imageId": "1",
"shopId": "3",
"imageUrl": "aaa",
},
{
"imageId": "2",
"shopId": "3",
"imageUrl": "bbb",
},
]
},
{
"shopId": "4",
"shopName": "2",
"address": "bbb",
"contactNumber":"1234"
"images": [
{
"imageId": "3",
"shopId": "4",
"imageUrl": "ccc",
},
{
"imageId": "4",
"shopId": "4",
"imageUrl": "ddd",
},
]
},
]
I got the values but some confusions in fetching the values.
You have two nested async tasks here, parallel and each.
Parallel takes care of getting the shop information and the images for one shop and calls the final callback with a two element array that has the results for your tasks.
This is your final callback for parallel:
function(err,data)
{
var result = data.reduce(function(prev, curr) { /*merging the array*/
return prev.concat(curr);
});
console.log(result);
});
data should be a two element array, where element 0 is the shop, and element 1 are the images. You just concatenate these together. If you want your images in the desired format, you should do data[0].images = data[1] to add the images key to your shop.
That so far is for one shop. Then there is the outer each loop. You are currently not giving this a final callback and not doing anything with the result.
Something like this:
function listshops(callback)
{
var array=[3,4];/*shopId*/
async.each(array,function(dat,eachCallback){
async.parallel([
function(parallelCallback){
client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
parallelCallback(null,data1);
});
},
function (parallelCallback) {
client.connection.query('select * from image where shopId=?',dat,function(err,data2){
parallelCallback(null,data2);
});
}
],
// this is the final callback for parallel
function(err,parallelResult)
{
// construct one shop
var shop = parallelResult[0];
shop.image = parallelResult[1];
// pass the shop info back as a result to each
eachCallBack(shop);
});
},
// this is the final callback for each
function(err, eachResult) {
// eachResult is an array with the shops returned from parallel callback
var result = {
shops: eachResult
}
return result
}
);
}
I couldn't test this, so don't consider it an exact solution, but an explanation. I renamed your variables for better understandability, you don't have to do that in your code. The key thing to keep in mind is that you have two nested tasks here, like a nested loop and you also have to deal with the results on two levels.

Resources