Is there any way to display 0 when an array is [""]? - javascript

I have an object that I'm iterating over using Object.keys(myData).map
const data = Object.keys(myData);
const output = data.map(key => (
{myData[key].bad.length} //correctly shows 2 for "bad" on "Bravo", but will show 1 for "bad" on "Charlie" when the array is[""]
));
Data
{
"Alpha": {
"bad": ["0001-00"],
"good": ["0002-00", "0003-00", "0004-00"],
"percent": 10,
"optionOne": true,
"optionTwo": false
},
"Bravo": {
"bad": ["0002-11", "0003-01"],
"good": ["0002-14", "0005-06"],
"percent": 75,
"optionOne": true,
"optionTwo": true
},
"Charlie": {
"bad": [""],
"good": ["0131-00", "0007-13", "0001-92"],
"percent": 25,
"optionOne": true,
"optionTwo": false
}
}
I have this to display how many items are in the array, but when they array is [""] it will display 1. Any suggestion on how I will be able to display 0 when there array is [""]?
I have all of my code working here: https://repl.it/repls/DapperHungryFraction

You could filter the array before taking the length.
This filters out empty strings:
myData[key].bad.filter(x=> x !== "").length;

Related

How do I rename & delete multiple keys in an array?

I am trying to build a pie chart in react js which uses highcharts (https://api.highcharts.com/highcharts/) is accepting only the following format for pie chart data (or maybe I'm wrong): Sample Fiddle here: https://jsfiddle.net/react_user1/e9cbsrdL/1/
data: [
{name: 'abc', y: 10},
{name: 'def', y: 90}
]
The data I get from my API looks something like this:
const counts:[
{
"id": "all",
"type": "all",
"count": 1403
},
{
"id": "bad",
"type": "bad",
"count": 0
},
{
"id": "failed",
"category": false,
"type": "failed",
"count": 58
},
{
"id": "changed",
"category": true,
"type": "changed",
"count": 123
}
So I am trying to achieve three things here:
1. Remove the first {}, with the "id": "all"
2. Rename the key: "id" to name & "count" to y
3. Remove the keys: "type" & "category" & their data
Thanks for any help you could provide, even a partial answer that can help would be appreciated.
I think you can use Array.prototype.filter() and Array.prototype.map() combination.
With filter() you can remove the value what you don't need - in your case all - then with map() you can create a new structure for you array.
From the documentations - link mentioned above:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Just like this:
const counts = [
{
"id": "all",
"type": "all",
"count": 1403
},
{
"id": "bad",
"type": "bad",
"count": 0
},
{
"id": "failed",
"category": false,
"type": "failed",
"count": 58
},
{
"id": "changed",
"category": true,
"type": "changed",
"count": 123
}
];
const result = counts.filter(f => f.id !== 'all')
.map(e => ({ name: e.id, y: e.count }));
console.log(result);
I hope this helps!
You can also provide data as an array of arrays:
series: [{
data: (() => counts.map(
item => [item.id, item.count]
))()
}]
Live demo: https://jsfiddle.net/BlackLabel/op4s13dm/
try this
renderarrayobjects = () => {
return this.state.arrayname.map((Arrayelement, Indexvalue) => {
return (
<View style={styles.btnColor}>
<Text style={styles.tagtext}>{Arrayelement}</Text>
<TouchableOpacity
Indexvalue={Indexvalue}
onPress={() => {
this.remove(Arrayelement);
}}>
<Image style={styles.editskill} source={deletarray} />
</TouchableOpacity>
</View>
);
}); };
The index value is the Index value.
this will render a list of Array items and we add an image that will be pressed to delete array the cross image will appear after every element of an array
removePeople(Arrayelement) {
var array = [...this.state.Arrayelement];
var index = array.indexOf(Arrayelement);
if (index !== -1) {
array.splice(index, 1);
this.setState({Arrayelement: array});
} }
this method will delete array objects.
Hope it helps .feel free for doubts

combining replacer and fields in json.stringify

How would I use white-list of fields and a replace function at the same time when using json.stringify?
How to stringify objects through JSON's replacer function?
explains how to use a field list.
Hide null values in output from JSON.stringify()
Has an answer for filtering null values: https://stackoverflow.com/a/41116529/1497139
Based on that code snippet i am trying:
var fieldWhiteList=['','x1','x2','children'];
let x = {
'x1':0,
'x2':null,
'x3':"xyz",
'x4': null,
children: [
{ 'x1': 2, 'x3': 5},
{ 'x1': 3, 'x3': 6}
]
}
function replacer(key,value) {
if (value!==null) {
if (fieldWhiteList.includes(key))
return value;
}
}
console.log(JSON.stringify(x, replacer,2));
And the result is:
{
"x1": 0,
"children": [
null,
null
]
}
Which is not what I expected. I would have expected the x1 values for the children to show up and not null values.
How could i achieve the expected result?
see also jsfiddle
By adding some debug output to the fiddle
function replacer(key,value) {
if (value!==null) {
if (fieldWhiteList.includes(key))
return value;
}
console.log('ignoring '+key+'('+typeof (key)+')');
}
I got the output:
ignoring x2(string)
ignoring x3(string)
ignoring x4(string)
ignoring 0(string)
ignoring 1(string)
ignoring 2(string)
{
"x1": 0,
"children": [
null,
null,
null
]
}
which showed that potentially the keys can be array indices. In this case they are all numbers from 0 to n in string format so:
adding a regular expression to match numbers fixed the issue
function replacer(key,value) {
if (value!==null) {
if (fieldWhiteList.includes(key))
return value;
if (key.match('[0-9]+'))
return value;
}
console.log('ignoring '+key+'('+typeof (key)+')');
}
with the expected output:
ignoring x2(string)
ignoring x4(string)
{
"x1": 0,
"x3": "xyz",
"children": [
{
"x1": 2,
"x3": 5
},
{
"x1": 3,
"x3": 6
},
{
"x1": 4,
"x3": 7
}
]
}

How to check if multiple objects in array have the same property value?

Hey guys I want to know what is the best approach to check wether two or more objects has the same property value in my case dueTo?
My array looks like this
Array [
Object
"__typename": "Instalment",
"_id": "5cd022cf0d805222374197eb",
"description": "Description",
"dueTo": "2019-05-16T23:00:00.000Z",
"instalmentAmount": 200000,
"paid": false,
},
Object {
"__typename": "Instalment",
"_id": "5cd022cf0d805222374197ea",
"description": "Description",
"dueTo": "2019-05-23T23:00:00.000Z",
"instalmentAmount": 200000,
"paid": false,
},
Object {
"__typename": "Instalment",
"_id": "5cd022cf0d805222374197e9",
"description": "Description",
"dueTo": "2019-05-23T23:00:00.000Z",
"instalmentAmount": 200000,
"paid": false,
},
]
First I want to know which objects include the value paid: false
const unpaidInstalments = instalments.filter(
instalment => !instalment.paid
);
Now I want to check if there are instalments in the same day in this case will result to index 1 and 2 and here the question come how do I filter this?
SOLVED
Get all the available dates and put them in an object then check if there is more than 1 object which contain the same value and return an array with these objects
const sameDayArray = unpaidInstalments.reduce(
(datesToCheck, instalment) => {
datesToCheck[instalment.dueTo] =
(datesToCheck[instalment.dueTo] || 0) + 1;
return datesToCheck;
},
{}
);
const instalmentsSameDay = unpaidInstalments.filter(instalment => {
return sameDayArray[instalment.dueTo] > 1;
});

Seperate items by an attribute type set in different arrays

I am trying to seperate items by an attribute named 'ProductGroupName' that is returned in the restful API. I want to loop through and create a seperate array for each section with the items listed as that attribute inside each.
I can manipulate my SQL on the server side to change how results are given but it would cause problems; here is an example result:
{
"message": "Success",
"data": [
{
"StockID": 69323,
"TradeName": "NAN OPTIPRO HA 1 GLD 800G",
"ProductGroupName": "BABY FOODS",
"SOH": 24,
"MinimumSOH": 0,
"Retail": 3199,
"AverageRetail": 0,
"Cost": 2848,
"RealCost": 2791,
"Reorder": true,
"Message": null,
"ListCost": null,
"Markup": 12,
"PLU": "476358",
"NoDiscount": true
},
{
"StockID": 18057,
"TradeName": "NAN PRO 2 GLD 800G",
"ProductGroupName": "BABY FOODS",
"SOH": 19,
"MinimumSOH": 0,
"Retail": 2050,
"AverageRetail": 0,
"Cost": 2301,
"RealCost": 1918,
"Reorder": false,
"Message": null,
"ListCost": null,
"Markup": -10,
"PLU": "436178",
"NoDiscount": true
},
{
"StockID": 74206,
"TradeName": "OPTIFAST VLCD SHAKE BANANA 12X53G (NEW)",
"ProductGroupName": "WEIGHT LOSS",
"SOH": 6,
"MinimumSOH": 0,
"Retail": 4799,
"AverageRetail": 0,
"Cost": 3937,
"RealCost": 3086,
"Reorder": true,
"Message": null,
"ListCost": null,
"Markup": 10,
"PLU": "294454",
"NoDiscount": true
}],
}
This is the standard output of all results though, so changing the result would complicate how I have written my REST service.
What is the best way to group these items?
I was considering looping through them, and when a new 'ProductGroup' is found, a new Array is created and that item is inserted, but that doesn't seem very optimised and I would like to know if theres a better way to achieve this.
One of the simplest way to organize the result of the request in a way you described in your question is to apply Array.prototype.reduce to result's "data":
result.data.reduce((acc, item) => {
const name = item['ProductGroupName'];
acc[name] = acc[name] || [];
acc[name].push(item);
return acc;
}, {});
With this approach you will get following object
{BABY FOODS: Array(2), WEIGHT LOSS: Array(1)}

How to get values of an array of dictionary from alamofire response using swift3

I'm trying to extract "translations" Array "text" and "verses" array "verse_key" data from below json response using Alamofire and swift3.
{
"verses": [
{
"id": 1,
"verse_number": 1,
"chapter_id": 1,
"verse_key": "1:1",
"text_madani": "بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ",
"text_indopak": "بِسْمِ اللّٰهِ الرَّحْمٰنِ الرَّحِيْمِ",
"text_simple": "بسم الله الرحمن الرحيم",
"juz_number": 1,
"hizb_number": 1,
"rub_number": 1,
"sajdah": null,
"sajdah_number": null,
"page_number": 1,
"audio": {
"url": "versesAbdulBaset/Mujawwad/mp3/001001.mp3",
"duration": 6,
],
"format": "mp3"
},
"translations": [
{
"id": 102574,
"language_name": "english",
"text": "In the name of Allah, the Beneficent, the Merciful.",
"resource_name": "Shakir",
"resource_id": 21
}
],
}
],
"meta": {
"current_page": 1,
"next_page": null,
"prev_page": null,
"total_pages": 1,
"total_count": 7
}
}
I'm new to swift and I can't find a way to achieve this. How can I get the values of "translations" Array "text" and "verses" array "verse_key" ?
thanks advance
Use swiftyJSON.
switch response.result{
case .success(let data) :
let json = JSON(data)
let verses = json["verses"].Stringvalue
print(verses) //get all verses
print(verses["verse_key"].Stringvalue) // get "verse_key"
break
You can take each values from this json by giving the key names. If you want to get the "verses" , use json["verses"].You can also use JSONdecoder.

Categories