How do I add values I got from forEach? (reactjs) - json

I'm trying to extract data from an API call that gives me this JSON:
JSON data:
{ "rows":
[
{
"customer_id": 1,
"customer_details":
{
"customer_id": 1,
"email":"john#mail.com",
"first_name":"John",
"last_name":"Doe",
"phone":"+123456123"
},
"order_items":[
{
"name": "random name",
"quantity":1
}
]
},
{
"customer_id": 2,
"customer_details":
{
"customer_id": 2,
"email":"johnny#mail.com",
"first_name":"Johnny",
"last_name":"Silverhand",
"phone":"+123456123"
},
"order_items":[
{
"name": "random name",
"quantity":1
},
{
"name": "another random name",
"quantity":1
}
]
}
]
}
I am actually able to get the the quantity but when there are two or more objects from the array in order_items like with customer 2, what I get is 11 how do I add the values I get? Sorry if this is really a simple problem but I am really confused.
here is my code for how I get them:
function getQuantity(qty) {
if(qty.length === 1) {
return qty[0].quantity;
} else {
let tempArr = [];
qty.forEach(prod => {
// console.log(prod.quantity)
tempArr.push(prod.quantity)
});
return tempArr;
}
}
I mapped used the function I made inside a map here is part of the code:
{orderList.map((val, key) => {
if (val.status_id !== 5) {
return (
<tr key={key} className='text-center'>
<td className='tdata'>{getQuantity(val.order_items)}</td>

Your getQuantity function returns an array of numbers (given this json data) and when you set the value of your td to be, as in your example, [1, 1] it will output "1""1" which will look like "11".
If you want to display the sum of your values, you could do something like this (although there is probably a better way to sum all the numbers in an array)
function getQuantity(qty) {
if(qty.length === 1) {
return qty[0].quantity;
} else {
let tempVal = 0;
qty.forEach(prod => {
tempVal += prod.quantity
});
return tempVal;
}
}

Related

Modify nested arrays in JSON (Groovy)

I'm trying to parse and mofidy JSON with Groovy. Source JSON from REST API looks like:
[
{
"id":27858,
"type":"ad",
"stats":[
{
"day":"2021-01-21",
"sex":[
{
"impressions_rate":0.349,
"value":"f"
},
{
"impressions_rate":0.621,
"value":"m",
"clicks_rate":0.22
}
],
"age":[
{
"impressions_rate":0.217,
"value":"18-21"
}
]
},
{
"day":"2021-02-25",
"sex":[
{
"impressions_rate":0.349,
"value":"f"
},
{
"impressions_rate":0.651,
"value":"m"
}
],
"age":[
{
"impressions_rate":0.217,
"value":"18-21"
}
]
}
]
},
{
"id":565291,
"type":"ad",
"stats":[
{
"day":"2021-03-21",
"sex":[
{
"impressions_rate":0.78,
"value":"f",
"clicks_rate":0.33
},
{
"impressions_rate":0.551,
"value":"m"
}
],
"age":[
{
"impressions_rate":0.17,
"value":"18-21"
}
]
}
]
}
]
It's an array with some ids and data for them. I want to grab id, day inside stats array and elements from sex array. After all manipulations my JSON should be like this:
[
{
"id": 27858,
"day": "2021-01-21",
"impression_rate": 0.349,
"value": "f"
},
{
"id": 27858,
"day": "2021-01-21",
"impression_rate": 0.621,
"value": "f",
"clicks_rate": 0.22
},
{
"id": 27858,
"day": "2021-02-25",
"impressions_rate":0.349,
"value":"f"
},
{
"id": 27858,
"day": "2021-02-25",
"impressions_rate":0.651,
"value":"m"
},
{
"id": 565291,
"day": "2021-03-21",
"impressions_rate":0.78,
"value":"f",
"clicks_rate":0.33
},
{
"id": 565291,
"day": "2021-03-21",
"impressions_rate":0.78,
"value":"f",
"clicks_rate":0.33
}
]
So, the main goal is - loop through all ids -> elements in sex array (for each id) and add to these elements day and id mapped fields. I tried to start with empty map with inject, but after 1 hour of debugging i still can't achieve desired output, so maybe better to loop through existed values in array? But I can't even reach sex array.
import groovy.json.*
def json = new JsonSlurper().parseText '''...'''
List expected = json.inject([]){ r, e ->
Map ids = e.findAll {
k, v -> k == "id"
}
e.each{ k, v ->
if( (v.any{ it.sex } )
v.each{ r << ids + it }
}
return r
}
If you have nested structures, that contain again nested structures,
a good option, to get a flat result, is to use collectMany; like
collect it transforms each item of the iterated container, but the
results gets concated.
E.g. you can collectMany on your outer data, then again on the
stats, and finally just collect over sex.
def data = new groovy.json.JsonSlurper().parse("data.json" as File)
println data.collectMany{ o ->
o.stats.collectMany{ i ->
i.sex.collect{ it + [id: o.id, day: i.day] }
}
}
// [[impressions_rate:0.349, value:f, id:27858, day:2021-01-21],
// [impressions_rate:0.621, value:m, clicks_rate:0.22, id:27858, day:2021-01-21],
// [impressions_rate:0.349, value:f, id:27858, day:2021-02-25],
// [impressions_rate:0.651, value:m, id:27858, day:2021-02-25],
// [impressions_rate:0.78, value:f, clicks_rate:0.33, id:565291, day:2021-03-21],
// [impressions_rate:0.551, value:m, id:565291, day:2021-03-21]]

Flutter and Json Retrieve a Title where value is

I have a Json array that is from wordpress. It retrives posts.
Each post has a serie of custom_options.
here an example:
{
"options":{
"wpcf-fields-select-option-f1d645c9017cce89714ede343df0cc73-1":{
"title":"-Select-",
"value":""
},
"wpcf-fields-select-option-3e64c784ce30a384e5167d1d6c1feb4e-1":{
"title":"1\/5",
"value":"S14"
},
"wpcf-fields-select-option-48334e061de93e6c47cc42c0fb5cd180-1":{
"title":"1\/8",
"value":"S1"
},
"wpcf-fields-select-option-a061ee2d2d302c5f42b2c93f9e811cdc-1":{
"title":"1\/12",
"value":"S2"
}
}
}
What I am trying to do is to call a function that will return the title of a given value.
Already tried using
// infoList is the json object
// resultVal is the value I am searching for
String getarrayinfos (infoList, resultVal) {
var result;
Map thisList = infoList;
for(var eachArr in thisList.keys){
if(thisList[eachArr]["value"] == resultVal){
result = thisList[eachArr]["title"];
}
}
return result.toString();
}
and printing it as the child of a container
// options is the json Object
// S7 is the value I am searching for
child: Text(getarrayinfos(options, "S7")),
but it prints the following error
flutter: type 'String' is not a subtype of type 'int' of 'index'
What am I doing wrong?
Instead of looking in infoList.keys look into infoList.values:
String getArrayInfo(Map theMap, String searchText) {
for (var val in theMap['options'].values) {
if (val['value'] == searchText) return (val['title']);
}
return 'not found';
}
void main() {
Map myMap = {
"options": {
"wpcf-fields-select-option-f1d645c9017cce89714ede343df0cc73-1": {
"title": "-Select-",
"value": ""
},
"wpcf-fields-select-option-3e64c784ce30a384e5167d1d6c1feb4e-1": {
"title": "1\/5",
"value": "S14"
},
"wpcf-fields-select-option-48334e061de93e6c47cc42c0fb5cd180-1": {
"title": "1\/8",
"value": "S1"
},
"wpcf-fields-select-option-a061ee2d2d302c5f42b2c93f9e811cdc-1": {
"title": "1\/12",
"value": "S2"
}
}
};
print(getArrayInfo(myMap, "S14"));
}

How to remove objoct from object by finding in type script

This is my object
"filterValue":[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}},
]
from this i want to search where value.Id = 2 and i want to remove that obeject line.
how can i do that..?
note:first value will be empty there is no data in value.
i have tried something like this:
filterValue.splice( filterValue.indexOf(2), 1 );
You can't use indexOf in this case because you are checking a complex object but you can use findIndex like this:
filterValue.splice( filterValue.findIndex(a => a.Id == 2), 1 );
You might want to change the code the check if findIndex actually found something by checking if it returns something larger than (or equal to) 0.
You can use filter to get a new filtered array (filteredArr):
var arr = [
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}}
];
var filteredArr = arr.filter((x) => JSON.stringify(x.value) !== JSON.stringify({"Id":"2"}));
console.log(filteredArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have a couple of subtly traps to avoid with your specific example.
The structure of items differs, so you need to be careful that you don't have a problem with the "--Select a Member--" item, which doesn't have a value.Id.
The example below cheaply solves the type issue (the best common type between the array members doesn't contain the property you are interested in).
const items = [
{ "label": "--Select a Member--", "value": "" },
{ "label": "ghi.jkl", "value": { "Id": "1", } },
{ "label": "abc.def", "value": { "Id": "2", } },
{ "label": "asd.vdf", "value": { "Id": "3", } },
];
const filtered = items.filter((i: any) => !i.value || !i.value.Id || i.value.Id !== '2');
console.log(filtered);
Output:
[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1"}},
{"label":"asd.vdf","value":{"Id":"3"}}
]
const obj = {
filterValue: [
{ label: "--Select a Member--", value: "" },
{ label: "ghi.jkl", value: { Id: "1" } },
{ label: "abc.def", value: { Id: "2" } },
{ label: "asd.vdf", value: { Id: "3" } }
]
};
var changedObj = obj.filterValue.filter((data, index) => {
return data.value.Id != "1";
});
console.log(changedObj);

How to update a key value in JSON dynamically?

I have a JSON like below
{
"context":{
"parameters":[
{
"name":"stub",``
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
I am supplied with a two strings dynamically like "cars" and "accord". I need to search for "cars" and then replace the "item value" under it to "accord". I have tried to convert it to map but have no success.
Any suggestions about how I can achieve this?
Here's one way to do it in Groovy.
Assuming that the JSON is like so (I have corrected it; there are illegal chars in the original question):
def s = '''
{
"context":{
"parameters":[
{
"name":"stub",
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
}
'''
then consider:
import groovy.json.*
def jsonSlurper = new JsonSlurper().parseText(s)
def category = jsonSlurper.context.parameters.find { it.name == "cars" }
category.value."item value" = "accord"
println new JsonBuilder(jsonSlurper).toPrettyString()
you can do that with javascript. If you are working with JSON format you can parse that data to an object.
const data = JSON.parse("your json data")
data.context.parameters.map(param => {
if ( param.name !== "cars") {
return param
}
return {
"name": "cars",
value: {"accord": "corolla"}
}
})

How to get total no of count of a field in a Json Array using TypeScript

I have a Json array.
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
Here I want to get the count of total number of customer. I am getting it like this:
json.user.value.length;
And the output is 3. But the thing is I have to avoid duplicate customer number.
As here "1234" is there 2 times. So my output should be 2
How to do this using Typescript.
Use lodash:
var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniqueCustomer.length
Here is link which shows How to use lodash in your app.
You can use Array.reduce to count the unique customers.
const data = {
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
};
function getCustomerCount(arr) {
let tmp = [];
return arr.reduce((acc, curr) => {
if(!tmp.includes(curr.customerNo)) {
return tmp.push(curr.customerNo);
}
return acc;
}, 0);
}
let customers = data.user.value;
let customerCount = getCustomerCount(customers);
console.log(customerCount);