coverting the string to json object - javascript

I tried to display my data in json format. Firstly i tried JSON.stringify
then it shows in string format so, then again I tried JSON.parse where I get like array of object finally I tried keeping [0] to the parse object it throws 'undefined'...
can you please tell me where I am doing wrong..
I provide the output of the following console.log..
try{
var timekeep = await Orders.findAndCountAll(
{
where : {
cid : orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
}
);
console.log("RESULT => ", timekeep);
var datjsn = JSON.stringify(timekeep);
var jsonsr = JSON.parse(datjsn);
var data23 = jsonsr[0];
console.log('alpha1'+ datjsn);
console.log('delta2'+ jsonsr);
console.log('beta'+ data23);
output of the console logs
RESULT => { count: 1,
rows:
[ orders {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
__eagerlyLoadedAssociations: [],
isNewRecord: false } ] }
alpha1 {"count":1,"rows":[ {"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}]}
delta2 [object Object]
beta undefined

var data23 = jsonsr[0];
In here you have took wrong place. Actually the data is in jsonsr.rows[0].
For this you can use,
jsonsr.rows[0];
or if the key value is not known use the Object.keys to get the all the objects in array and proceeding with loop with the condition of check the object value in array and length greater than 0 can get the all the datas.

The object is sequelize object not just object.
Try to use .get()
var timekeep = await Orders.findAndCountAll(
{
where : {
cid : orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
}
);
console.log(timekeep.rows[0].get())

Related

How do I get array of values from a nested object in Javascript

I am trying to create record from a form data. When I console.log(req.body) I get the following record.
req.body => [Object: null prototype] {
id: '1',
key1: 'Value1',
key2: 'Value2',
supervisors: '[object Object],[object Object],[object Object]'
}
So I checked the database where the record is stored and see that supervisors is stored as:
supervisors: Array(3)
0:
name: "Reporter"
userId: 4
1:
name: "Officer 1"
userId: 5
2:
name: "Coordinator"
userId: 2
I will like to get the values of userId as an array in supervisors field in the req.body so that my req.body will look like:
req.body => [Object: null prototype] {
id: '1',
key1: 'Value1',
key2: 'Value2',
supervisors: '[4, 5, 2]'
}
I did const supervisors = JSON.stringify(req.body.supervisors)) and I got [object Object],[object Object],[object Object] when console logged
I did const supervisors = q.supervisors ? JSON.parse(q.supervisors) : []; and I got SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse when console logged.
I did const supervisors = req.body.supervisors.map(sup => sup.userId); and I got req.body.supervisors.map is not a function when console logged.
How can I get the supervisors value as [2, 4, 5]?
Use map()
const supervisors = q.supervisors.map(sup => sup.userId);
You don't need to use any JSON functions, as the data you show has already been parsed into an array of objects.
As mentioned above, map() is the correct one-line approach.
map() using an arrow function (which has an implicit return) is also the ideal approach if you need to chain further transformations.
The alternative (verbose but also lightning-fast) approach is (that old work-horse) the for loop.
Working Example:
// THE OBJECT
const myObject = {
supervisors: [
{
name: 'Reporter',
userId: 4
},
{
name: 'Officer 1',
userId: 5
},
{
name: 'Coordinator',
userId: 2
}
]
};
// THE SUPERVISORS ARRAY (NOT YET POPULATED)
const supervisors = [];
// LOOP THROUGH THE ARRAY IN THE OBJECT TO POPULATE THE SUPERVISORS ARRAY
for (let i = 0; i < myObject.supervisors.length; i++) {
supervisors.push(myObject.supervisors[i].userId);
console.log(supervisors);
}

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,
]
});

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)

Why isn't omit() removing the undefined values after mapping?

I'm using the following Lodash chained utilities to map/flat and array and produce a new one while excluding the undefined valued.
const array = _(resp.data)
.omit(_.isUndefined)
.flatMap('building')
.value()
console.log(array)
And this is the result:
As you can see the undefined values are still being included. Why is this?
EDIT:
resp.data looks like this
[
{ username: '', building: [ name: '' ] }
{ username: '', building: [ name: '' ] }
// etc...
]
EDIT2:
Those undefined values are probably the empty building that come objects have.
The extra undefined value should belong to a user in the resp.data where no building exist. All you have to do is to _.filter() all values that are undefined through _.identity() after the _.flatMap().
Note: Using _.omit should only be used against objects, using this in the context of an array (e.g. _.flatMap() which results in an array) would yield a result of an object wherein the index of each item is it's index in the array. You should use _.filter() instead.
var data = [
{ username: 'user1', building: [ { name: 'building1' } ] },
{ username: 'user2', building: [ { name: 'building2' } ] },
{ username: 'user3' }
];
var result = _(data)
.flatMap('building')
.filter(_.identity)
.value();
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>
Try this.
const array = _(resp.data)
.omit(_.isUndefined)
.flatMap('building')
.map()
.omit(_.isUndefined)
.value()

How to iterate an array of objects in Javascript

I have an object (obj) that contains the content of an excel sheet (using node-xlsx library).
console.log(obj) gives me the following data structure:
[ { name: 'Autostar Report',
data:
[ [Object],
[],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[],
[object]
]}]
Each of the objects in data contain values like this:
[
8,
"Enugu - Abuja",
"Sienna Executive ( 1st )",
5,
"9,000",
"45,000",
"5,500",
"39,500"
],
[
14,
"Enugu - Lagos",
"Sienna Executive ( 1st )",
5,
"9,000",
"45,000",
"8,600",
"36,400"
]
Each of the object contained in data contains 8 values. I want to insert the values into a database table. Each of the value goes to a field in the table.
Please how do I access the values in each data object?
Note that you keep saying "object", when really the obj.data value is an array of arrays. With arrays, you access a value by numerical index.
So, given your data structure, and the fact that you have only selected javascript, you would access the data like so:
// ensure the object has a "data" attribute
if (obj.hasOwnProperty('data')) {
// get the data into a variable for convenience
var data = obj.data;
// loop over each row
for (i = 0; i < data.length; i++) {
// put the row into a variable for convenience
var row = data[i];
// since it's an array, access each value by index
console.log(row[0]);
console.log(row[1]);
console.log(row[2]);
// ... etc ...
}
}
Here's a working fiddle
When it comes to processing things like this, a library such as underscore or lodash sure come in handy.

Categories