How to get a length of this JSON Object? - javascript

I have the following object stored in my LocalStorage, How do I get the .length of everything? I'm trying to get the total amount of records (without DT_RowID)?
This is what I'm working with:
const cartLength = Object.values(JSON.parse(localStorage.getItem('todo'))).flat().length;
console.log("JSON obj length: ", cartLength);
here is my json object (as is)
{
"15894903752910": {
"Name": "John",
"Grade": "",
"Gender": "F",
"DOB": "2013/07/10",
"DT_RowId": "15894903752910" <--- this must be excluded in the 'items' count
},
{
"15894903752911": {
"Name": "Jane",
"Grade": "",
"Gender": "F",
"DOB": "2003/07/10",
"DT_RowId": "15894903752910" <--- this must be excluded in the 'items' count
}
....
}
The result of this should be 2 records and 8 items

Very confusing question but to get a count of all the record keys, excluding DT_RowId, something like this...
const todos = JSON.parse(localStorage.getItem('todo'))
const records = Object.values(todos)
console.log('total records', records.length)
const itemLength = records.map(r => Object.keys(r).filter(k => k !== 'DT_RowId'))
.flat().length

I think you want to count the keys:
Object.keys(myObject).length
Is that what you wanted?

Related

Remove numeric values from an object where the values are all strings but a mix of letter and numbers [duplicate]

This question already has answers here:
How can I check if a string is a valid number?
(50 answers)
Closed 2 months ago.
I have to call an api that returns an array of objects:
"supervisors": [
{
"jurisdiction": "u",
"lastName": "Olson",
"firstName": "Karson"
},
{
"jurisdiction": "9",
"lastName": "Heller",
"firstName": "Robbie"
},
{
"jurisdiction": "b",
"lastName": "Cremin",
"firstName": "Elijah"
},
]
The supervisors must be sorted in alphabetical order, first by jurisdiction, then my last name, finally by first name.
Then Numeric jurisdictions should be removed from the response.
I sorted alphabetically by:
supervisorsObj.sort((a, b) => {
a.jurisdiction.toLowerCase().localeCompare(b.jurisdiction.toLowerCase());
});
But how do I remove Numeric jurisdictions if they are all strings?
One option would be to use regular expressions, e.g
filtered = data.supervisors.filter(s => !/^\d+$/.test(s.jurisdiction))
will only remove jurisdictions that consists entirely of digits.
The following snippet will first filter out all numeric .jurisdiction entries and will sort the remaining entries in a case-insensitive manner according to jurisdiction, lastName, firstName:
const supervisors= [
{
"jurisdiction": "u",
"lastName": "Olson",
"firstName": "Karson"
},
{
"jurisdiction": "9",
"lastName": "Heller",
"firstName": "Robbie"
},
{
"jurisdiction": "b",
"lastName": "Cremin",
"firstName": "Elijah"
},
{
"jurisdiction": "b",
"lastName": "Cremmin",
"firstName": "Elijah"
},
{
"jurisdiction": "b",
"lastName": "Cremin",
"firstName": "Daniel"
},
{
"jurisdiction": "b",
"lastName": "Cremin",
"firstName": "eddie"
}
];
const res=supervisors.filter(s=>isNaN(parseFloat(s.jurisdiction)))
.sort((a,b)=>{
let ab=0;
["jurisdiction","lastName","firstName"].some(p=>ab=a[p].toLowerCase().localeCompare(b[p].toLowerCase()));
return ab;
});
console.log(res);
The actual comparisons take place in the inner .some() loop. The loop will stop processing as soon as it generates a result ab that is not equal to zero.

Count multiple values in JSON object and print to screen

I have been searching the web for this, and can only seem to locate the Object.keys(obj).length which counts the length of the JSON. I am looking to loop through the JSON and count the values which are the same. In an Array of JSON objects.
[
{
"name": "Bob",
"age": 36
},
{
"name": "Billy",
"age": 18
},
{
"name": "Bob",
"age": 45
}
]
For example, I want to count many Bob there are. I would like to then output to a component like so.
There were 2 Bob
How can this be achieved? In certain situations I will know that there could only be say 4 values for example. SITE, MOBILE, CTV, VIDEO etc, I forsee collecting them and counting them would be easier than counting a random result.
const input = [
{
"name": "Bob",
"age": 36
},
{
"name": "Billy",
"age": 18
},
{
"name": "Bob",
"age": 45
}
]
let sums = input.reduce((a, r) => {
a[r.name] ??= 0
a[r.name] ++
return a
}, {})
console.log(sums)
Now use sums variable to print data in any form you like.

how to get particular Keys Values from the exiting JSON Object in javacsript? [duplicate]

This question already has answers here:
How to get a subset of a javascript object's properties
(36 answers)
Closed 3 years ago.
I have one JSON Object and I want to create subset of JSON with particular keys values.
JSON Object
{
"Checksum": "OK",
"ID": "012B4567",
"DOB: "12-12-1991"
"Data": "Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>",
"issue: "11-April-2015",
"DocID": "PASSPORT",
"Number: "123456789",
"Document": "PASSPORT",
"Photo": "Qk06AAAAAAAAA",
"ExpiredFlag": false,
"ExpiryDate": "01 Apr 12",
"Forename": "IMA Phoney",
"Image2": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"ImageSource1": 0,
"Image3": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"Image1": "/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I want subset from above like below:
{
"ID": "012B4567",
"Number: "123456789",
"Document": "PASSPORT",
"IssueState: "USA",
"Nationality": "USA",
"PlaceOfBirth": "U.S.A",
"SecondName": "J",
"Sex": "Male",
"Surname": "XYZ"
}
I have tried below code. It is working fine, But I am not able to understand. I need simplest way:
var data={
"CDRValidation": "CDR Validation test passed",
"AirBaudRate": "424",
"ChipID": "012B4567",
"BACStatus": "TS_SUCCESS",
"SACStatus": "TS_NOT_PERFORMED",
"Data": "Test Line 1 >>>>>\nTest Line 2 >>>>>\nTest Line 3 >>>>>",
"DocType": "PASSPORT",
"DocNumber": "123456789",
"DocID": "PASSPORT",
"Surname": "Person",
"Forename": "IMA Phoney",
"SecondName": "J",
"Nationality" : "Imaging Automation Demo State",
"Sex": "Male",
"DOB": "12 May 70",
"ExpiryDate": "01 Apr 12",
"IssueState": "Passport Agency Billerica",
"ExpiredFlag": false,
"ImageSource": 0,
"OptionalData1": "123456789123456",
"OptionalData2": "",
"DateOfIssue":"11 April 02",
"PlaceOfBirth":"Illinois, U.S.A"
}
console.log("----------------->",data);
var Fields = ({
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data, {
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
})
console.log("--------subset--------->",Fields);
There are multiple ways you can handle this case. Object destructuring as you have done in your example is one simple way. You can also use an array to store the required keys and write code as below
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
const obj = {};
for (let i = 0, length = keys.length; i < length; i += 1) {
obj[keys[i]] = parentObj[keys[i]];
}
return obj;
}
Or you can also use the above code with some functional programming
function subset(parentObj) {
const keys = ['key1', 'key2', 'key3'];
return keys.reduce((acc, key) => ({
...acc,
[key]: parentObj[key];
}), {});
}
A simple to achieve what you are asking using ES5 is to create a list of all the properties you want to keep, and using Array#reduce add each property to a new object.
// Saves vertical space for example
var original = JSON.parse(`{"Checksum":"OK","ID":"012B4567","DOB":"12-12-1991","Data":"Test Line 1 >>>>>↵Test Line 2 >>>>>↵Test Line 3 >>>>>","issue":"11-April-2015","DocID":"PASSPORT","Number":"123456789","Document":"PASSPORT","Photo":"Qk06AAAAAAAAA","ExpiredFlag":false,"ExpiryDate":"01 Apr 12","Forename":"IMA Phoney","Image2":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","ImageSource1":0,"Image3":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","Image1":"/9j/4AAQSkZJRgABAQEBkAGQAAD/2wBDAAgGBgcGBQgHBwcJCQ","IssueState":"USA","Nationality":"USA","PlaceOfBirth":"U.S.A","SecondName":"J","Sex":"Male","Surname":"XYZ"}`);
var propertiesToUse = ["ID", "Number", "Document", "IssueState", "Nationality", "PlaceOfBirth", "SecondName", "Sex", "Surname"];
var result = propertiesToUse.reduce(function(result, key) {
return result[key] = original[key], result;
}, {});
console.log(result);
What you have done is a simple way, but if you are confused with it, you can divide it into two lines and explain it.
This line actually destrucutes your object and assign the value for the mentioned keys in the object to the corresponding variables.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
} = data
Now, each of this variable has data individually, but we want it in an object. Therefore, we use the second part, i.e. creating an object with the following variable acting as keys.
{
IssueState,
ExpiryDate,
DateOfIssue,
PlaceOfBirth,
DOB,
Sex,
DocNumber,
DocType
}
When combined you get the desired result in a single statement.

for each does not work on object array when you filter

I m trying to get all the numbers from the list of all the contacts. Im probably not using forEach correctly any advice? I've put a sample of what is expected
//sample of a contact
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
//Expected
numbers = [
5557664823,
7075551854
]
//does not work
const numbers = contacts.map(contact => contact.phoneNumbers.forEach(number));
forEach always returns undefined, so your map callback returns undefined, so numbers will be full of undefineds.
I think you probably want to return the phone numbers (each number in the phoneNumbers array of each entry), and then perhaps flatten the result:
const numbers = contacts.map(contact => contact.phoneNumbers.map(({number}) => number)).flat();
Array.prototype.flat is relatively new, but easily polyfilled.
That's such a common pattern that there's a flatMap method to do it in one go:
const numbers = contacts.flatMap(contact => contact.phoneNumbers.map(({number}) => number));
Or just a simple loop with push:
const numbers = [];
for (const {phoneNumbers} of contacts) {
numbesr.push(...phoneNumbers.map(({number}) => number));
}
Probably want to use reduce and map
let numbers = contacts.reduce((p, c, i) => {
return p.concat(c.phoneNumbers.map(pn => pn.number));
}, []);
I don't know how many times I've done that. forEach doesn't return anything.
const numbers = contacts.reduce((n, c)=>(a.concat(contact.phoneNumbers)),[]);
or
const numbers = contacts.reduce((n, c)=>(a.concat(contact.phoneNumbers.map(pn=>pn.number)),[]);

Loop over JSON items whether JSON object has multiple arrays or not

I have a working version of a function to loop through a single array in a JSON object, e.g.
[{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}]
sample function:
function FindName(NameToFind, data1) {
objData = JSON.parse(data1);
for (var i = 0; i < objData.length; i++) {
var Name = objData[i].Name;
if (Name == NameToFind) {
alert("found!");
}
}
}
Now I need to change this function to allow for either single OR multiple arrays e.g.
{
"Table1": [{
"Name": "John",
"Surname": "Johnson"
}, {
"Name": "Peter",
"Surname": "Johnson"
}],
"Table2": [{
"Name": "Sarah",
"Surname": "Parker"
},
{
"Name": "Jonah",
"Surname": "Hill"
}
]
}
Is there a way to determine whether the object has 1 array (like in first example) or more than one arrays (like in 2nd example), and any advice/guidance on how to extend the function to be able to loop through all the items whether it has 1 array or multiple arrays?
Your first object is an array, the second one isn't.
You can test if your argument is an array, or even just test
if (objData[0]) // that's an array
EDIT :
if you want to iterate over all properties of a (just json decoded) object, when it's not an array, you can do this :
for (var key in objData) {
var value = objData[key];
// now use the key and the value
// for example key = "Table1"
// and value = [{"Name":"John","Surname":"Johnson"}, ... ]
}

Categories

Resources