JSON always starts with [null - javascript

I have an array that contains plenty of data. The format is always like that:
1:
UserName: "John Smith"
Priority: "2"
Time Occured: "02/09/2019 11:20:23"
Time Ended: "02/09/2019 11:20:23"
2:
UserName: "Tom Bill"
Priority: "4"
Time Occured: "01/08/2019 13:20:23"
Time Ended: "04/08/2019 15:20:23"
3:
UserName: "John Smith"
Priority: "2"
Time Occured: "06/08/2019 13:20:23"
Time Ended: "09/09/2019 15:20:23"
...
Then I am changing this one into json file but it always starts with:
[
null,
{
I am using JSON.stringify to make it work
result = JSON.stringify(array);
I have tried a few options, yet unfortunately it always ends with null at the beginning. Is there any way to remove the null from the beginning of the json, or maybe to replace it?

My advice would be to check why null is always the first item, but if you really can't change that, then you can use .shift() to remove the first element of the array before you stringify it:
const array = [null, 1, 2, 3, 4]
// this removes the first element
array.shift()
JSON.stringify(array)
>>> "[1, 2, 3, 4]"

We can also use this method to remove null, undefined, NaN, empty string from array use this code. This will filter the array. After filtering you can Stringify it:
Array=[null,1,2,3,null,4,undefined,7,NaN,"",8,]
// this removes the null,undefined,NaN,"" from this Array
var filtered = Array.filter(function(el) { return el; });
JSON.stringify(filtered)
console.log(filtered) //"[1, 2, 3, 4, 7, 8]"

Related

Using [Sequelize.Op.in] for json object arrays

I have a meta tag table which contains a tagId and a value.
I have an array of tagId,value objects
Eg : [{'tagId':2, 'value':33}, {'tagId':2, 'value':34}, {'tagId':1,
'value':34}, etc.. ]
My metaTag table consists of a virtual column which will return the {tagId,value} object for each entry in table. My question is how can I select rows with each {tagId, value} pair in the array.
In other words, I want to be able to do something like
[Sequelize.Op.in]:[{'tagId':2, 'value':33}, {'tagId':2, 'value':34}]
This doesn't work, however.
I might not have explained this well, English isn't my first language. Please ask if you need any clarification on the issue.
You can attain this by using Op.or. If I am not wrong you are trying
('tagId' = 2 and 'value' = 33) or ('tagId' = 2, 'value' = 34):
where: { [Sequelize.Op.or]: [{'tagId':2, 'value':33}, {'tagId':2, 'value':34}] }
You can add n number of values to the or array. As per your requirement.
if you want to do a in like this:
tagId in(2, 2) and value in (33, 34) then:
where: {'tagId':[2], 'value':[33, 34]}
You don't need the explicit Op.in for the array.
You can use there:
const myDeviceIds = [1, 2, 3, 4, 7, 9, 29];
const macroDevices = await MacroDevice.findAll({
where: {
deviceId: {
[Op.in]: myDeviceIds,
},
life: {
[Op.not]: null,
},
status: {
[Op.is]: null,
}
},
order: [
['id', 'DESC']
],
limit,
offset,
include: [
Macro,
Targets,
]
});

Loop through array of objects, check for a matching parameter and add the matching object to new array

I'm new to JS and React and I'm a little stuck here. I've searched through SO but I'm having trouble finding a solution with an explanation that works.
Here are my arrays.
The first array is pretty simple.
[1, 3, 4,]
The second looks like this.
[
{
id: 1,
title: Title 1,
},
{
id: 2,
title: Title 2,
},
]
What I'd like to do is search the second array and if I can find an id that matches a value in the first array, add the object from the second array to third, new array.
I've tried a number of things and I'm sure there's a relatively easy way to do this with a forEach loop or lodash but I'm coming up blank.
Any help and explanations would be greatly appreciated.
Thanks,
Your second array is not valid. You have to wrap the string values with quotes.
You can use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes()
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Try the following way:
var arr1 = [1, 3, 4,];
var arr2 = [
{
id: 1,
title: 'Title 1',
},
{
id: 2,
title: 'Title 2',
},
];
var res = arr2.filter(i => arr1.includes(i.id));
console.log(res);

Iterating over array of JSON objects in TypeScript gives me individual characters at indices

I have an array of JSON objects received from an API call.
data = [{
"notificationId": null,
"notificationText": "xXXX YYY",
"notificationType": "typeA",
"fromId": 2,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898875,
"nano": 0
}},
{
"notificationId": null,
"notificationText": "YYYYYYY,
"notificationType": "typeB",
"fromId": 3,
"toId": 9,
"timestampCreated": {
"epochSecond": 1493898903,
"nano": 0
}}
]
I want the individual Notification objects, by iterating over this array
My Notification interface looks like below
interface Notification {
notificationId: number;
notificationText : string;
notificationType : string;
fromId:number;
toId:number;
timestampCreated: Date ;
}
notif: Notification[] = [];
.
.
this.notif =data;
for(var i=0;i<this.notif.length ;i++){
console.log("notification text at "+this.notif[i].notificationText);
//this gives undefined
//and it loops through all the characters of the data
// not just twice
}
Can some one help, I am very new to angular2/ typescript world.
I am answering this as I figured out what was the problem. In the above snippet, the array of objects is actually array of JS objects not JSON objects. So I needed to parse the objects before I could use them as JSON. A simple JSON.parse(data) fixed the issue.

Replacing special character with jquery

i need to replace the special character "[" and "]" in this syntaxe:
var Data = "[{\tst??}]";
It's a json format and i need to show all the information individually so i need a tip in jquery to replace or delete the "[" and "]" they causing me troubles when i whant to show the information.
Thank you.
var Data = "...."; // here is your data
var obj = JSON.parse(Data);
after this, obj will contain:
[ { AccountNumber: '664009500',
AccountNumberLong: '230100950070',
Autorizations: [],
AvailableBalance: 0,
Balance: 2243.93,
BeneficiaryList: [ [Object], [Object], [Object], [Object], [Object] ],
CanCreditAccount: true,
CanDebitAccount: true,
CodeOffre: 'CPTCHQ11',
Currency: 'MAD',
EligibleServiceList: [ '300014', '300018', '300013', '300016' ],
Entitled: 'MONSIEUR HOUSSAM MOUBTAHIL',
IsDemat: 'true',
LstClientidTuteur: null,
OpeningDate: '/Date(1408662000000+0000)/',
OperationDate: '/Date(-62135596800000+0000)/',
OperationLastDate: '/Date(1465776000000+0000)/',
OperationOAA: null,
OperationOSD: null,
Operations: null,
RelationType: null,
SitexAccountList: [],
SitexTierList: null,
TotalBalance: 0,
TotalCredit: 32151.26,
TotalDebit: 29255.77,
legalSituation: 'MJ' } ]
nothing to change :)
you have a list of objects, if your list will have only one element - take obj[0], if more - just loop through them (using, for loop or jQuery's .each)..
Use slice to remove the first and the last char (i.e, [ and ])
CleanData=Data.slice(1, -1);
Use this to remove all [ followed by { in order to get only { and the same is for }] that are replaced with }. In this way, something like [] is not replaced
var res = Data.replace("[{","{");
var CleanData=res.replace("}]","]");
try to use : Data.toString().trim().replace("[", anotherCharacter)

What is the format of Express' req.params?

I've got a weird thing I'm running into with req.params while working with Express. It works fine for calling the subordinate properties - e.g.: res.json(req.params.paramName); gives me the desired paramName value. But when I tried to pass the entire res.params object to the client via res.json(req.params), I just get an empty array [] in the browser instead of the JSON object I was expecting. (res.send gives the same result.)
Looking a bit deeper, I dumped req.params to the console:
console.dir(req.params);
and got this:
[ creator: '1', timeStart: '2', timeEnd: '3', dateDensity: '4' ]
wut? Is that even syntactically possible in Javascript?
If req.params is a simple object like the Express code and documentation indicate, I should be getting:
{ creator: '1', timeStart: '2', timeEnd: '3', dateDensity: '4' }
An array like what I'm getting above should even be possible, should it?
I did some sanity checks and passed a couple of test objects to the console as well:
console.dir([{foo:1}, {arr:2}, {gog:3}, {blah:4}]);
console.dir({foo:1, arr:2, gog:3, blah:4});
and the console dump gives me:
[ { foo: 1 }, { arr: 2 }, { gog: 3 }, { blah: 4 } ]
{ foo: 1, arr: 2, gog: 3, blah: 4 }
So console.dir is working OK.
Lastly, I hardcoded a:
res.json({foo:1, arr:2, gog:3, blah:4});
into my Express code and the browser dutifully gives me:
{
"foo": 1,
"arr": 2,
"gog": 3,
"blah": 4
}
Am I smoking crack here? What is going on with req.params?
That's how v8 prints out arrays with string keys:
var myArr = [];
myArr.key = "oops";
Remember, [] instanceof Object is true.
req.params is an array, suggesting the possibility of positional params.

Categories