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.
Related
I'm working on a project for myself (gotta keep busy). I have JavaScript that taps API, and retrieves data as follows:
{
'2020-12-18:95': {
'45.0': [ [Object] ],
'50.0': [ [Object] ],
'55.0': [ [Object] ],
'60.0': [ [Object] ]
}
}
How do I enumerate through that? When I
object.2020-12-18:95
to get to the strike prices, I get error mesg. Your help is appreciated 😀
You can try using Object.keys() and .map() to iterate through as:
const data = {
'2020-12-18:95': {
'45.0': [ {} ],
'50.0': [ {} ],
'55.0': [ {} ],
'60.0': [ {} ]
}
}
const result = data['2020-12-18:95']
Object.keys(result)
.map(key => console.log(key, result[key]))
From the documentations:
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
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,
]
});
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())
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)
If I had control over an IteratorModel object that told me information I need to compare the children arrays how could I compare the two arrays?
An IteratorModel would be an object like this:
var iteratorModel = {
next: {
name: 'Next',
next: {
name: 'NextNext',
boolProp: 'HighlightNextNext'
}
}
};
The name property gives us the name of the next level of data in our arrays. Each level can have additional information as well, but that isn't important to the question.
So if this was the basic structure of comparing arrA and arrB how could I use the iteratorModel to compare nested arrays?
$.each(arrA, function (i, valA) {
$.each(arrB, function (b, valB) {
// what to do here?
});
});
More info:
Given two arrays that follow this general structure:
MasterArray: [
{
id: 0,
NestedArr: [
{
id: 0,
NestedNestedArr: [
{
id: 0
}
],
More Objects...
}
],
More Objects...
},
More Objects...
]
How could I dynamically compare them not knowing the level of NestedArrays, but instead given an IteratorModel?