Calculation on dynamic data in React - reactjs

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

Related

How do I get the sum of two json objects?

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);

Convert Array of Objects into Array of Array of strings

In my angular app, I get the values from service as an array of objects like below.
temp= [
{
"a": "AAA",
"b": "bbbb",
"c": "CCCC",
"d": "ddddd",
},
{
"a": "lmn",
"b": "opq",
"c": "rst",
"d": "uvw",
}
]
I need to format this temp to array of array of strings:
newTemp =
[
['AAA', 'bbbb', 'CCCC', 'ddddd'],
['lmn', 'opq', 'rst', 'uvw'],
];
Should we need to do a forloop on each object or is there any straight forward way.
You can use Array.map
let newArray = arr.map(a => Object.values(a))
If you cant use Object.values
let newArray = arr.map(a => Object.keys(a).map(k => a[k]))
Output
(2) [Array(4), Array(4)]
0:(4) ["AAA", "bbbb", "CCCC", "ddddd"]
1:(4) ["lmn", "opq", "rst", "uvw"]
Try the following :
temp= [
{
"a": "AAA",
"b": "bbbb",
"c": "CCCC",
"d": "ddddd",
},
{
"a": "lmn",
"b": "opq",
"c": "rst",
"d": "uvw",
}
]
var newTemp = [];
temp.forEach(function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push(obj[key]);
})
newTemp.push(arr);
});
console.log(newTemp);

How to modify a complex JSON Object in using Immutable

I have below JSON and wanted to update the value depending on Aid, Bid and Cid using Immutable.js
e.g.
Below input provided.
Aid= A, Bid = 1, Cid= 4, NewValue = 'FOUR'
If above input is provided the value "One" needs to be changed to "FOUR"
let sampleJson = {
Aid: 'A', detail:"sample", list: [
{
"Bid": "1",
"group": [
{
"name": "Group A",
"Cid": "4",
"value": "One"
},
{
"name": "Group A",
"Cid": "41",
"value": "1"
},
]
},
{
"Bid": "2",
"group": [
{
"name": "Group A",
"Cid": "4",
"value": "1"
},
{
"name": "Group A",
"Cid": "4",
"value": "1"
},
]
};
I was able to access the value using below code. How can i return the entire JSON with updated value?
let variale = Immutable.fromJS(sampleJson).
getIn(['list']).
find(allocation => allocation.get("Bid") === "1").
getIn(['group']).
find(fun => fun.get("Cid") === "4").set('value',"FOUR");
Anyone has any suggestions on how to resolve this problem?
I think you can try to do this like so:
let immutable = Immutable.fromJS(sampleJson);
immutable = immutable.setIn(['list', 0, 'group', 0, 'value'], 'FOUR');
This monstrosity is how I would do it:
const newData = originalData.update('list', list => {
const itemIndex = list.findIndex(item => item.get('Bid') === '2');
return list.update(itemIndex, listItem => {
return listItem.update('group', groupList => {
const groupIndex = list.findIndex(group => group.get('Cid') === '4');
return groupList.update(groupIndex, group => {
return group.set('value', 'FOUR');
});
});
});
});
https://jsbin.com/latupo/7/edit?html,js,console
Personally I stopped using Immutable, I always found it a bit painful (not to mention those docs!). I now use redux and good old cloning to not mutate state. Less performant in theory but if you've got nothing that runs over a few milliseconds anyway, save yourself the trouble...

Remove common elements from JSON Objects in Array

I have an array of objects and I am looking to remove all the elements from the objects and their sub-objects that are common across all objects.
Maybe the best way to explain this is with an example
[
{
"a": {
"k1": [1,2,3],
"k2": 4
},
"b": {
"k3": {
"foo": "bar",
"top": "bottom"
},
"k4": 5
},
"c": {
"k5": [{"cat":"dog"},{"rat":"not rat"}]
},
"d": { }
},
{
"a": {
"k1": [1,2,3],
"k2": -4
},
"b": {
"k3": {
"foo": "hat",
"top": "bottom"
},
"k4": 5
},
"c": {
"k5": [{"cat":"dog"},{"rat":"mouse"}]
}
}
]
would evaluate to
[
{
"a": {
"k2": 4
},
"b": {
"k3": {
"foo": "bar"
}
},
"c": {
"k5": [{"cat":"dog"},{"rat":"not rat"}]
},
"d": { }
},
{
"a": {
"k2": -4
},
"b": {
"k3": {
"foo": "hat"
}
},
"c": {
"k5": [{"cat":"dog"},{"rat":"mouse"}]
},
"d": null
}
]
Are there any good tools I can use to solve this? I looked at json-diff but that doesn't quite fit my requirements.
I wrote some julia functions to do this for me
I started by computing the common fields in the objects and then proceeded to remove the common fields from each of the objects.
function common_in_array(a::Array)
common = deepcopy(a[end])
common_in_array!(a[1:end-1], common)
end
function common_in_array!(a::Array, common::Dict)
if size(a,1) == 0
return common
else
return common_in_array!(a[1:end-1], dict_common!(a[end], common))
end
end
function dict_common!(d::Dict, common::Dict)
keys_d = keys(d)
keys_common = keys(common)
all_keys = union(keys_d, keys_common)
and_keys = intersect(keys_d, keys_common)
for k in setdiff(all_keys, and_keys)
delete!(common, k)
end
for k in and_keys
v1 = d[k]
v2 = common[k]
if typeof(v1) != typeof(v2)
delete!(common, k)
elseif isa(v2, Dict)
dict_common!(v1, v2)
elseif v1 != v2
delete!(common, k)
end
end
common
end
function remove_common_from_dict!(d::Dict, common::Dict)
for (key, value) in common
if key in keys(d)
value_d = d[key]
if value == value_d
delete!(d, key)
elseif isa(value, Dict) && isa(value_d, Dict)
remove_common_from_dict!(value_d, value)
end
end
end
d
end
function remove_common_from_array!(a::Array, common::Dict)
map(d -> remove_common_from_dict!(d, common), a)
end
function remove_common_from_array!(a::Array)
remove_common_from_array!(a, common_in_array(a))
end
then I evaluate this on my json_array string
using JSON
JSON.print(remove_common_from_array!(JSON.parse(json_array)))

How to create an array of dictionaries?

new to programming!
I'm trying to create an array of dictionaries inside a struct in Swift like so:
var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [[ : ]]
myArray.append(dictionaryA)
myArray.append(dictionaryB)
This works fine in a playground, but when I put it into an Xcode project, inside a struct, the lines with the append function produce the error "Expected declaration".
I've also tried using the += operator with the same result.
How can I successfully construct this array inside the struct?
From your error Expected declaration, I assume you are doing like:
struct Foo {
var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [[ : ]]
myArray.append(dictionaryA) // < [!] Expected declaration
myArray.append(dictionaryB)
}
This is because you can place only "declarations" in the struct body, and myArray.append(dictionaryA) is not a declaration.
You should do that somewhere else, for example in the initializer. The following code compiles.
struct Foo {
var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [[ : ]]
init() {
myArray.append(dictionaryA)
myArray.append(dictionaryB)
}
}
But as #AirspeedVelocity mentioned, you should provides more information about myArray, or myArray would be Array<NSDictionary> which I think you don't expect.
Anyway, the correct solution would vary depending on what you really trying to do:
Maybe or maybe not, what you want is something like:
struct Foo {
static var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
static var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [dictionaryA, dictionaryB]
}
But, I don't know, why don't you just:
struct Foo {
var myArray = [
[
"a": "1",
"b": "2",
"c": "3",
],
[
"a": "4",
"b": "5",
"c": "6",
]
]
}
The problem lies with this line:
var myArray = [[ : ]]
You need to tell Swift what type myArray is – [[:]] isn’t enough information.
You can either do it the explicit way:
var myArray: [[String:String]] = [[ : ]]
Or, if practical, implicitly using the first or both values you plan to put in:
var myArray = [dictionaryA]
var myArray = [dictionaryA,dictionaryB]
(as an alternative to the explicit empty version, you can also write var myArray = [[String:String]](), which is shorthand for var myArray = Array<Dictionary<String,String>>())
var arrayOfDict = [[String: Int]]()
// Create a dictionary and add it to the array.
var dict1: [String: Int] = ["age": 20]
arrayOfDict.append(dict1)
// Create another dictionary.
var dict2: [String: Int] = ["rank": 5].
arrayOfDict.append(dict2)
// Get value from dictionary in array element 0.
if let value = arrayOfDict[0]["age"] {
print(value)
}
Output
20
Or you can use an array of tuples that´s even easier, like this:
var myArray:[(a:String,b:String,c:String)] = []
And append any element you need later:
self.myArray.append((a:"A",b:"B",c:"c"))
And to use them just:
self.myArray[index].a
self.myArray[index].b
self.myArray[index].c

Resources