I want to get specific data from JSON array in adonisjs. But I have some problem to get that data. When I'm looping this JSON array the return just only empty array = []. This is my controller code:
const detail= await TrxHistory.query()
.where('id_trx', params.id_trx)
.fetch()
This return json array:
[
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_confirm",
"created_at": "2019-10-18 22:27:54"
},
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_process",
"created_at": "2019-10-18 22:29:48"
},
]
And i'm try to get data from row "trx_status", using looping like this:
let data = [];
for(var i = 0; i < detail.length; i++) {
data[i] = detail[i]["trx_status"];
}
console.log(data);
What's wrong with this code?
When you fetch adonis lucid request you need to use .rows. Like:
... // Your query
let fooData = [];
detail.rows.forEach(de => {
fooData.push(el.trx_status)
})
How to use?
detail.rows[1]
detail.rows.length
If detail has a structure that you've shown, then it should work perfectly:
const detail = [
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_confirm",
"created_at": "2019-10-18 22:27:54"
},
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_process",
"created_at": "2019-10-18 22:29:48"
},
];
let data = [];
for (let i = 0; i < detail.length; i++) {
data[i] = detail[i]["trx_status"];
}
console.log(data);
// another way:
let fooData = [];
detail.forEach(el => {
el["trx_status"] ? fooData.push(el["trx_status"]) : null;
});
console.log(fooData);
Related
I have a project in Typescript in which I am trying to create a function that converts an array into an object using the first values as keys of the object.
This is my array:
let testArr = ["id", "ser", "add", "1", "asd", "82.255", "2", "ert", "82.119", "3", "pol", "82.250"];
This is what I need:
let newArr = [
{
"id": "1",
"ser": "asd",
"add": "82.255"
},
{
"id": "2",
"ser": "ert",
"add": "82.119"
},
{
"id": "3",
"ser": "pol",
"add": "82.250"
}
]
In result I store the data of the array that I want to use as keys of the object:
let chunk = 3;
let result = testArr.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index/chunk)
if(!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [] // start a new chunk
}
resultArray[chunkIndex].push(item)
return resultArray
}, [])
My problem is that I don't know how to use that data as keys of the object and I would like to know how to convert the result variable into a generic function for any array and any number.
You can iterate over the testArr array using forEach and check the index. if it's a multiple of 3 you can assign an object with the values and push that object to the new array.
For your case, i've modified the answer to a generic case where you can pass the starting index of the values in the original array
let testArr = ["id", "ser", "add", "1", "asd", "82.255", "2", "ert", "82.119", "3", "pol", "82.250"];
const arr = [];
function genericArrayFormatter(checkIdx){
testArr.forEach((val, idx) => {
if (idx > checkIdx - 1 && idx % checkIdx === 0){
const obj = {};
let i = 0;
let index = idx;
while (checkIdx > i){
obj[testArr[i++]] = testArr[index++];
}
arr.push(obj);
}
});
}
genericArrayFormatter(3);
console.log(arr);
I would like to compare JSON values to an array of values but I d'ont know what's the best scenario to go with.
I got a JSON object with expected values (could have 1 value , 2 or more)
I have a DB function that returns a fix number of values, say 10 values all the time and I would like to know if my JSON values matches the right one coming from DB.
Ex:
My JSON var is :
var expValues = {
"id": "123",
"age": 23
};
My DB will push some values to an Array of objects.
Ex:
if ((rs.BOF) && (rs.EOF))
{
//nothing found;
}
else
{
while (!rs.EOF)
{
aDetails.push(
{
"id": rs.fields("id").Value,
"name": rs.fields("name").Value,
"age": rs.fields("age").Value,
"sex": rs.fields("sex").Value,
"hobby": rs.fields("hobby").Value
});
rs.MoveNext();
}
}
rs.close;
//Close connection then return
return aDetails;
basically I want to make sure values coming from JSON match the right ones coming from DB. (id for example).
I have assumed aDetails to have something like below data.
let aDetails = [{
"id": "123",
"name": "as",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "1234",
"name": "as1",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "12",
"name": "as2",
"age": 23,
"sex": "m",
"hobby": "abc"
}]
var expValues = {
"id": "123",
"age": 23
};
function isObjectMatched(obj) {
return aDetails.some(d => Object.entries(obj).every(([k, v]) => d[k] == v))
}
console.log(isObjectMatched(expValues))
This is a general purpose way of indexing list of objects for fast retrieval with any configuration of properties.
// javascript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
listOfPropertyToIndex.forEach((p) => {
key.push(""+o[p]);
});
return key.join("_");
};
arrayOfObject.forEach((o) => {
index[objToKey(o)] = o;
});
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
// jscript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
for (var p in o) {
if (o.hasOwnProperty(p)) {
key.push(""+o[p]);
}
}
return key.join("_");
};
for (var i = 0; i < arrayOfObject.length; ++i) {
index[objToKey(arrayOfObject[i])] = o;
}
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
Here is how to use it
var expValues = {
"id": "123",
"age": 23
};
var index = makeIndex(aDetails, ["id","age"]);
var obj = index.match(expValues);
if (obj) {
... obj ...
}
var index_name = makeIndex(aDetails, ["name"]);
var person = {"name":"as2"};
var obj2 = index_name.match(person);
if (obj2) {
... obj2 ...
}
"results": {
"code": "SUCCESS",
"msg": [
{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}
]
},
this is my example code,where ever we have \n consider as header elements of table and \t consider as tr elements,can you provide me any suggestion.
You might be looking something like this. In your HTML code right one ng repeat for head and other for each row of the table.
var result = {
"code": "SUCCESS",
"msg": [{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}]
}
var format = result.msg.map((r) => {
var str = r.data;
var arr = str.split('\n');
var head = arr.splice(0, 1)[0].split('\t');
arr.pop(); // remove empty string
var data = arr.map((d) => {
return d.split('\t').reduce((obj, x, index) => {
obj[head[index]] = x;
return obj;
}, {})
})
return {
head,
data
}
});
console.log(format);
var res =
{
"response": {
"data": {
"profilesearchsnippet": [
[
{
"profileInfo": {
"firstname": "Sundar",
"lastname": "v"
},
"roleInfo": {
"defaultphotoid": 94
}
}
],
[
{
"profileInfo": {
"firstname": "ghg",
"lastname": "vbhvh"
},
"roleInfo": {
"defaultphotoid": 171
}
}
]
]
}
}
$scope.profileData = [];
I have a response var res . I need to pass my defaultphotoid to another request and form URL for displaying the image. which I pushed in $scope.images and I need to display all list of images along with respective firstname and lastname. But I couldnt do it. somewhere I am lacking it.
I pushed firstname and lastname in array by creating object in $scope.profileData
$scope.searchData = res.response.data.profilesearchsnippet;
for (var i = 0; i < searchData.length; i++) {
$scope.profileData.push({
'fname':searchData[0].profileInfo.firstname,
'lname':searchData[0].profileInfo.lastname
});
}
The above $scope.profileData [] has exact values what I am pushing , But I could push the values of images from $scope.images into this.
$scope.profileData.push({'image': images[i]});
what happen in above case is the first array has fname and lname object and second array object has image.
When you push into an array, it is added as a separate object in the array. If you want the image to be added along with fname and lname, add it in the loop itself like :
$scope.profileData.image = images[i];
If you already has the $scope.images array, You can add the image too in the same for loop you are using to add lName and fName like this :
for (var i = 0; i < searchData.length; i++){
$scope.profileData.push({'fname':searchData[i].profileInfo.firstname,'lname':searchData[i].profileInfo.lastname, 'image':$scope.images[i]});
}
try like this
$scope.searchData = res.response.data.profilesearchsnippet;
for (var i = 0; i < searchData.length; i++){
$scope.profileData.push({'fname':searchData[0].profileInfo.firstname,'lname':searchData[0].profileInfo.lastname, 'image':''});
}
Then:-
for (var i = 0; i < $scope.images.length; i++){
$scope.profileData[i].image = $scope.images[i];
}
I got a Json file like;
{
"Cities": [
{
"Name": "London",
"Country": "UK"
},
{
"Name": "Rome",
"Country": "ITA"
},
{
"Name": "Antalya",
"Country": "TR"
}
]
}
How can I get City Names as an array like ["London","Rome","Antalya"] without doing;
var tempJSON = JSON.parse(jsonCities);
var arrayCityNames = [];
for (var i = 0; i < tempJSON.Table.length; i++){
arrayCityNames[i] = tempJSON.Table[i].Name;
}
if tempJSON was a Dataset we could use getColumnArray
arrayCityNames = Data.Dataset.getColumnArray("Name");
Is there any built in method to do this for parsed JSON's?
Please keep in mind that the question is related to Smartface.io Framework, not jquery itself
Try this:
var tempJSON = JSON.parse(jsonCities);// here you load your JSON
var arrayCityNames = []; // your output array
var cityArray = tempJSON['Cities']; // enter Cities array
for (var i = 0; i <cityArray.length; i++){ // iterate over your list
arrayCityNames.push(cityArray[i]['Name']); // add to list name of your city list
}