How do you delete an empty array from javascript? - javascript

For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}

Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.

I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)

You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}

Related

Using Lodash to transform data into object properties instead of a collection by specifying properties value

following up on my previous question about transforming data using lodash, this time i require output to be an object properties instead of being a collection. I appreciate the help and if someone can also guide me where to begin properly so i have a better understanding of these concepts
Sample Data
{
"changeAccount": {
"add": [
{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
}
],
"remove": [
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
}
]
},
"changeproduct": {
"add": [
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
],
"remove": []
}
}
Expected Result
var sample = [{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
},
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
},
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
]
Here is one way to do it:
chain(data)
.values()
.map(_.values)
.flatMapDeep()
.value()
So what's happening here is:
Start with our data which is an object
Use .values to return only the values of our top level properties (i.e. strip away changeProduct and changeAccount
Map the resulting items in the array to only the values of our objects (i.e. strip away add and remove) using .values again
Flatten the entire array recursively so we end up with an array that is one level deep using .flatMapDeep
You might also notice the chain(data) syntax, this is just a way to improve the readability and sometimes performance of your lodash code, so that you don't have to nest each lodash function that you use. Check out the docs on chain for more info.

What is the best way to replace text in json?

So I have a bunch of JSON data and it contains a few fields. for example:
[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
what I'm trying to do is kind of conversion table (from a different JSON file)
if a field has the value 'a' replace it with 'some other text..' etc.
I have a service for the JSON pipeline, so I guess this is the right place to do the replacement.
so for this example, I have the JSON above and in my conversion table I have the following terms:
next: forward,
song: music,
a: option1,
just: from
etc...
What you are looking for can be achieved with templates. Replace the variable sections with some specific markers that you can find and replace from some external tools such as perl or sed.
For example, you could have a template.json with something like this:
...
"type": {
"value": "##VALUE##"
}
...
Then when you need the actual JSON, you could pass this though an intermediate script that replaces these templates with actual data.
cat template.json | sed -e 's/##VALUE##/my_value/' > target.json
Alternatively, with Perl:
cat template.json | perl -pi -e 's:\#\#VALUE\#\#:my_value:' > target.json
The best way is to parse it, replace the text in the object, and then stringify it.
The next best way is to use a regular expression.
In this example, I catch exceptions if path cannot be indexed, and use ['type'] instead of .type so it will scale to indexing 'non-type' if you wish.
const data = `[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
`
const o = JSON.parse(data)
o[0].body.forEach(b => {
try {
if (b.extended.spl['type'].value === 'a') {
b.extended.spl['type'].value = 'CHANGED'
}
} catch (e) {}
})
const newData = JSON.stringify(o, null, 2)
console.log(newData)
A string replace approach will work if you know and can rely on your source conforming, such as the only "value" is inside "type"
const data = `[{
"id": "XXX",
"version": 1,
"head": {
"text": "Main title",
"sub": {
"value": "next"
},
"place": "secondary"
},
"body": [{
"id": "XXX1",
"info": "three little birds",
"extended": {
"spl": {
"text": "song",
"type": {
"value": "a"
}
}
}
},
{
"id": "XXX2",
"info": [
"how are you?"
],
"extended": {
"spl": {
"text": "just",
"non-type": {
"value": "abc"
}
}
}
}
]
}]
`
const newData = data.replace(/"value": "a"/g, '"value": "NEWVALUE"')
console.log(newData)

Json Structure- How to read this JSON structure in javascript?

Can anyone help me to fetch the comments value from the below json structure.
Actually i want the id(very first column after items) for which the no of comments is 0. I m able to read the id but unable to put the if condition (comment =0) return {id}
"data": {
"posts": {
"items": [
{
"id": ,
"content": {
"id": ,
"files": [],
"user_details": {
"firstname": "",
"lastname": ""
},
"comments": "",
"tags": [
"anonymous"
],
"likeCount": 0,
"group_details": {
"group_name": "",
"guid":
},
"propertytags": {
"empty": ""
},
"permalink": {
"link":
},
"isFollowed": ,
"followerCount": "",
"favorite": "",
"isLiked": ""
},
"contentType": "",
"group_details": {
"group_name": ,
"guid":
}
}
How to read comments value?????
data.posts.items[index].content.comments will give you the value of comments.
However to fetch the id based on comment value, you may use Array.filter() function.
let result = data.posts.items.filter(item => {
if (item.content.comments === "0") {
return item.id;
}
});
result will be an array of id for which the comments is 0.
Here is an example with the data you've shared JS Bin

Add key values dynamically to nested object in Javascript

This might be a duplicate of this but did not get proper solution over there. I have object as below,
var replyDataObj = {
"department": {
"name": getCache("departmentName")
},
"subject": replyEmailSubject,
"payload": {
"email": {
"contents": {
"content": [
{
"type": "html",
"value": replyEmailContent
}
]
},
"emailAddresses": {
"from": fromEmailId,
"to": {
"address": [
toEmailId
]
}
}
}
}
}
I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,
"cc": {
"address": [
ccEmailId
]
}
So it will look like,
var replyDataObj = {
"department": {
"name": getCache("departmentName")
},
"subject": replyEmailSubject,
"payload": {
"email": {
"contents": {
"content": [
{
"type": "html",
"value": replyEmailContent
}
]
},
"emailAddresses": {
"from": fromEmailId,
"to": {
"address": [
toEmailId
],
"cc": {
"address": [
ccEmailId
]
}
}
}
}
}
}
I tried to add this using object[key] as below, object.key but no luck
replyDataObj[payload][emailAddresses][cc]={
"address": [
ccEmailId
]
}
I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.
Put strings inside []:
replyDataObj['payload']['emailAddresses']['cc']={
"address": [
ccEmailId
]
}
As answered by #K.Kirsz, I was missing strings inside [] (quotes). Also added missing 'email' key to solve my issue.
replyDataObj['payload']['email']['emailAddresses']['cc']={
"address": [
ccEmailId
]
}

How do I console.log one value of this JSON Object?

I am new to javascript and to JSON, so please forgive me.
If I have the following JSON Object, how would I console.log() out the value of autonum?
{
"database": "testdb",
"table": "path",
"affectedColumns": [
{
"name": "autonum",
"charset": null,
"type": 8
},
{
"name": "TimeStamp",
"charset": null,
"type": 18,
"metadata": {
"decimals": 0
}
},
{
"name": "FilePath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirPath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "EventName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileExt",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 10
}
},
{
"name": "FileSize",
"charset": null,
"type": 3
},
{
"name": "MainFlag",
"charset": null,
"type": 1
},
{
"name": "DeleteFlag",
"charset": null,
"type": 1
},
{
"name": "Status",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 255
}
},
{
"name": "ProcessedFlag",
"charset": null,
"type": 1
}
],
"changedColumns": [],
"fields": {
"autonum": 121,
"TimeStamp": "2016-01-13T00:21:13.000Z",
"FilePath": "c:/1E0304F120151223030158001.mp4",
"DirPath": "c:\\",
"DirName": null,
"EventName": null,
"FileName": "1E0304F120151223030158001.mp4",
"FileExt": ".mp4",
"FileSize": 2218108,
"MainFlag": 0,
"DeleteFlag": 0,
"Status": null,
"ProcessedFlag": 0
}
}
Depending on which autonum you want, and assuming your variable storing the JSON is data, you'll want to do something as follows:
console.log(data.fields.autonum);
or
console.log(data.affectedColumns[0].name);
You'd use the following code, assuming the json object is called record:
console.log(record.fields.autonum);
You have two main ways of doing it. Both are correct ways. Lets say your object is named obj. Use console.log as following:
console.log(obj.fields.autonum)
console.log(obj['fields']['autonum'])
First case is easier as compare to second case.
Second case is safer as it will allow you to even take care of keys which have spaces e.g.
var my_other_object = {
'Santa Clara': 'USA',
'Toronto': 'Canada'
};
console.log(my_other_object['Santa Clara']) // Output will be 'USA'
For your understanding, in above object 'Santa Clara' and 'Toronto' are called 'keys' of my_other_object and 'USA', 'Canada' are called 'values' of those 'keys'.
So JSON object is essentially combination of key:value pairs.
P.S. Never apologize while asking a question all questions are valid but it is good to always search before asking. Still, people are always happy to help here. We all have went through same phases. :)
Lets say your object name var data, then data.fields.autonum would give us value 121
console.log(data.fields.autonum)
Just FYI:
As it is stated on MDN website:
some JavaScript is not JSON, and some JSON is not JavaScript
Just in order to improve understanding of vocabulary, 'JSON Object' is not a thing in our context ... it is
a syntax for serializing objects

Categories