sequelize aggregate function gives wrong result - javascript

I'm newbie and sequelize aggregate function makes me confused because it gave me different result than expected. I'm trying to get a total price with sequelize.fn('sum', ...), and somehow sequelize only gives me the the total of first data of the associated model instead of summing all the result. My code as follows:
Training.findAll({
where: {
owner_id: payload
},
attributes: ['id', [sequelize.fn('sum', sequelize.col('training_classes.price')), 'totalPrice']],
include: [{
model: TrainingClass,
as: 'training_classes',
attributes: ['id', 'price'],
}],
group: ['Training.id', 'training_classes.id']
})
And the result of the query :
[
{
"id": "45",
"totalPrice": "300000",
"training_classes": [
{
"id": "94",
"price": "300000"
}
]
},
{
"id": "8",
"totalPrice": "1000000",
"training_classes": [
{
"id": "14",
"price": "1000000"
},
{
"id": "15",
"price": "300000"
},
{
"id": "16",
"price": "200000"
}
]
},
{
"id": "47",
"totalPrice": "100000",
"training_classes": [
{
"id": "97",
"price": "100000"
}
]
},
{
"id": "39",
"totalPrice": "1000000",
"training_classes": [
{
"id": "81",
"price": "1000000"
},
{
"id": "82",
"price": "300000"
}
]
},
{
"id": "24",
"totalPrice": "300000",
"training_classes": [
{
"id": "46",
"price": "300000"
}
]
},
{
"id": "6",
"totalPrice": "200000",
"training_classes": [
{
"id": "11",
"price": "200000"
}
]
},
{
"id": "49",
"totalPrice": "100000",
"training_classes": [
{
"id": "100",
"price": "100000"
},
{
"id": "99",
"price": "1000000"
},
{
"id": "101",
"price": "100000"
}
]
},
{
"id": "20",
"totalPrice": "200000",
"training_classes": [
{
"id": "38",
"price": "200000"
},
{
"id": "35",
"price": "400000"
},
{
"id": "37",
"price": "500000"
},
{
"id": "36",
"price": "100000"
}
]
},
]
as you can see, the totalPrice only from the first element of training_classes, not the entire data of it. How can I resolve this? Thank you in advance

If you want to sum all records in TrainingClass that have the same Training.id then you need to indicate no attributes for TrainingClass and indicate only Training.id in group option:
Training.findAll({
where: {
owner_id: payload
},
attributes: ['id', [sequelize.fn('sum', sequelize.col('training_classes.price')), 'totalPrice']],
include: [{
model: TrainingClass,
as: 'training_classes',
attributes: [],
}],
group: ['Training.id']
})
If you group by TrainingClass.id then you'll get grouped results for each record that has unique TrainingClass.id value and literally every record of TrainingClass has unique id value.

Related

Objects data to be updated with value from Array

I'm trying to update the 'positionTitle' field of my graphData object with the 'positionTitle fields of my individualData array.
I need to do it accurately, both sets of data have 'accounts' which both have the same id and fullname for user, I was hoping to try and use this to do the matching.
I want the positionTitle's from the users with same account id or name (whichever is easier) to go into the objects fields.
This is currently what I have:
My Object (that i want to update):
graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
}
My array whose positionTitles I want to take:
IndividualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
]
The function I'm currently using, which does take the first positiontitle field of the array:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
positionTitle: IndividualData[0].positions[0].positionTitle
}
}))
}))}))
}))
};
console.log(updatedGraphTable)
console.log('a' + JSON.stringify(updatedGraphTable))
my expected result with the positions updated:
updatedGraphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Managing Director"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Managing Director"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
My current result:
{
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
}, {
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334",
"account": {
"id": "eefe"
},
"position": {
"id": "3434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"position": {
"id": "4545",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}, {
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
}, {
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34",
"account": {
"id": "3546"
},
"position": {
"id": "3999434",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}, {
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546",
"account": {
"id": "3545"
},
"position": {
"id": "35006",
"positionTitle": "Senior Manager, Energy"
}
}]
}]
}]
}]
}
Sure, the trick would be to first map your data into an object (so you don't have to search over both arrays all the time), and then conditionally set the value (as I saw that your first manager, doesn't really have a matching position).
So to create the dictionary for usage in your later model, you can first do
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
This would then have an object where accountIdToPositionDict["123"] would be Managing Director, and then change the duplicating logic into:
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
Where the position would then be set based on the found accountId in the dictionary, or the original title if no match was found
const individualData = [{
"account": {
"id": "001b000003WnPy1AAF",
"fullName": "jeff bint"
},
"positions": [{
"id": "a16b0000004AxeBAAS",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Senior Manager, Energy",
"positionLevel": "5-Middle Management & Advisers",
"isPrimary": true,
"startDate": "2016-10-07",
"endDate": null
}]
}, {
"account": {
"id": "0010X000048DDMsQAO",
"fullName": "edy long"
},
"positions": [{
"id": "a160X000004nKfhQAE",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}, {
"account": {
"id": "123",
"fullName": "john boer"
},
"positions": [{
"id": "325345634634",
"organizationId": "001b0000005gxmlAAA",
"organizationName": "a",
"positionTitle": "Managing Director",
"positionLevel": "4-Head of Business Unit/Head of Region",
"isPrimary": true,
"startDate": "2018-03-05",
"endDate": null
}]
}
];
const graphData = {
"name": "Annual meetings",
"engagementAreas": [{
"id": "1",
"engagementTypes": [{
"name": "forestry",
"engagements": []
},
{
"name": "houses",
"engagements": [{
"name": "engagement1",
"members": [{
"id": "e334", "account": {
"id": "eefe", "fullName": "jim bean"
},
"position": {
"id": "3434",
"positionTitle": "Manager"
}
}]
}]
},
{
"name": "landscaping",
"engagements": [{
"name": "engagement1343",
"members": [{
"id": "e334", "account": {
"id": "123", "fullName": "john boer"
},
"position": {
"id": "4545",
"positionTitle": "Senior Manager"
}
}]
}]
}
]
},
{
"name": "community days",
"engagementTypes": [{
"name": "skyscraping",
"engagements": []
},
{
"name": "tennis",
"engagements": [{
"name": "engagement346",
"members": [{
"id": "34", "account": {
"id": "0010X000048DDMsQAO", "fullName": "edy long"
},
"position": {
"id": "3999434",
"positionTitle": "Ultime Manager"
}
}]
}]
},
{
"name": "Juicing",
"engagements": [{
"name": "347343",
"members": [{
"id": "4546", "account": {
"id": "001b000003WnPy1AAF", "fullName": "jeff bint"
},
"position": {
"id": "35006",
"positionTitle": "Senior Ultimate Manager"
}
}]
}]
}]
}]
};
// first map the accountId to positions
const accountIdToPositionDict = individualData.reduce( (current, item) => {
current[item.account.id] = (item.positions.filter( position => position.isPrimary )[0] || {} ).positionTitle;
return current;
}, {} );
// then use it in the mapping function
const updatedGraphTable = { ...graphData,
engagementAreas: graphData.engagementAreas.map(area => ({ ...area,
engagementTypes: area.engagementTypes.map(type => ({ ...type,
engagements: type.engagements.map(engagement => ({ ...engagement,
members: engagement.members.map(member => ({ ...member,
position: { ...member.position,
// use the found positionTitle, or the original one that was given
positionTitle: member.account && accountIdToPositionDict[member.account.id] || member.position.positionTitle
}
}))
}))}))
}))
};
console.log( updatedGraphTable );
Try the code below.
accountPositions = {};
IndividualData.forEach((data) => {
accountPositions[data.account.id] = data.positions.filter((pos) => {return pos.isPrimary})[0].positionTitle;
});
graphData.engagementAreas.forEach((area) => {
area.engagementTypes.forEach((type) => {
type.engagements.forEach((engagement) => {
engagement.members.forEach((member) => {
if (!accountPositions[member.account.id]) return;
console.log('position updated from ', member.position.positionTitle, 'to', accountPositions[member.account.id]);
member.position.positionTitle = accountPositions[member.account.id];
});
});
});
});

How can I return nested array with lodash?

I have some json and would like to return some nested objects, this is the json:
{
"existingPackage": {
"primaryBundle": {
"id": "2031",
"serviceId": "114297251",
"name": "TV - Entertainment, Drama, Movies",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Drama",
"id": "104",
"price": 2000,
"gifted": false,
"swappableProducts": [
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
},
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false,
"swappableProducts": [
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
}
]
}
}
}
The goal is to return only items from the productsarray which have the swappableProducts property and have a certain id.
So for example when I an productId = 105 then I would like to return:
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false,
"swappableProducts": [
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
}
}
How can I return this with lodash?
Here's my approach:
_.filter(
products,
i => _.every([
_.has(i, 'swappableProducts'),
_.eq(_.result(i, 'id'), '105')
])
);
The idea is to pass both predicates to every(). The first uses has() to check if the swappableProducts property exists. The second predicate combines eq() and result() to check the id value.
You could do something like this
_.filter(data.existingPackage.primaryBundle.products,
function(o) {
return o.swappableProducts !== undefined && o.id==="105";
});
Here's a function that returns desired result
const getProducts = obj => obj.existingPackage.primaryBundle.products;
const withSwappable = _.curry((myId, obj) => _.result(obj, 'swappableProducts[0].id', false) == myId)
function getProductsWithId(data, myId) {
return _.filter(getProducts(data), withSwappable(myId))
}
const data = {
"existingPackage": {
"primaryBundle": {
"id": "2031",
"serviceId": "114297251",
"name": "TV - Entertainment, Drama, Movies",
"products": [{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Drama",
"id": "104",
"price": 2000,
"gifted": false,
"swappableProducts": [{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}]
},
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false,
"swappableProducts": [{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}]
}
]
}
}
}
console.log(getProductsWithId(data, "107"));
console.log(getProductsWithId(data, "100"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

How to return a childobject from json with lodash?

Suppose I have the following json file and I would like to return the 'existing.primaryBundle.products' array preferrably with lodash:
{
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}
]
}
]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [
{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
},
{
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
},
{
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}
]
}
}
}
I have tried lodash and use this statement:
list2 = _.pick(existing,'primaryBundle.products')
But this returns an error and not the wanted result. How can I select this products array?
you could use _.get(nameOfObject, 'existing.primaryBundle.products') of course you would need to name your object like I've done below with sampleObject;
check out the lodash docs too
const sampleObject = {
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
}, {
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}]
}]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
}, {
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
}, {
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}]
}
}
}
console.log(_.get(sampleObject, 'existing.primaryBundle.products'));
The main reason why it returns an error is because existing is not a global scoped object, you have to assign object to some variable like const obj = {...} and then pass the parameter to _pick method as obj.existing, yet I don't see a reason to use lodash in here, you can just reference the path to that object directly.

Get deep object along with parent

Below is the sample data(Hierarchical data) I want to only that array of object which has IsChecked = true and also all its children with condition isChecked =true.
$scope.treedData = [{
"id": "1",
"text": "Women",
"parentId": null,
"IsChecked": true,
"children": [{
"id": "4",
"text": "Jeans",
"parentId": "1",
"IsChecked": true,
"children": [
{ "id": "5", "text": "Jeans child", "parentId": "4", "IsChecked": true, "children": [] },
{ "id": "6", "text": "Jeans child child", "parentId": "4", "IsChecked": false, "children": [] }
]
}]
},
{
"id": "2",
"text": "Men",
"parentId": null,
"IsChecked": false,
"children": [{ "id": "10", "text": "Sweatshirts", "parentId": "2", "IsChecked": false, "children": [] }]
},
{
"id": "3",
"text": "Kids",
"parentId": null,
"IsChecked": true,
"children": [{ "id": "12", "text": "Toys", "parentId": "3", "IsChecked": false, "children": [] }]
}
];
You can use reduce for that, and use recursion to apply the filter to the children hierarchy as well:
var treeData = [
{ "id": "1", "text": "Women", "parentId": null, "IsChecked": true,
"children": [
{ "id": "4", "text": "Jeans", "parentId": "1", "IsChecked": false, "children":[
{ "id": "5", "text": "Jeans child", "parentId": "4", "IsChecked": true, "children":[] },
{ "id": "6", "text": "Jeans child child", "parentId": "4", "IsChecked": false, "children":[] }
] }]
},
{ "id": "2", "text": "Men", "parentId": null, "IsChecked": false,
"children": [{ "id": "10", "text": "Sweatshirts", "parentId": "2", "IsChecked": false, "children":[]}]
},
{"id": "3", "text": "Kids", "parentId": null, "IsChecked": true,
"children": [{ "id": "12", "text": "Toys", "parentId": "3", "IsChecked": false, "children":[] }]
}
];
checkedTreeData = treeData.reduce(function checkedOnly (acc, obj) {
return obj.IsChecked
? acc.concat(Object.assign({}, obj, { children: obj.children.reduce(checkedOnly, []) }))
: acc;
}, []);
console.log(checkedTreeData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
NB: In JavaScript there is an unwritten rule to not use an initial capital letter for property names, so IsChecked would be with a lower case i: isChecked. Initial capital letters are commonly used for constructors (classes).
Alternative with .filter()
function filterChecked(treeData) {
return treeData.filter(obj => obj.IsChecked)
.map(obj => Object.assign({}, obj, obj.children ?
{ children: filterChecked(obj.children) } : {}))
}
var treeData = [
{ "id": "1", "text": "Women", "parentId": null, "IsChecked": true,
"children": [
{ "id": "4", "text": "Jeans", "parentId": "1", "IsChecked": false, "children":[
{ "id": "5", "text": "Jeans child", "parentId": "4", "IsChecked": true, "children":[] },
{ "id": "6", "text": "Jeans child child", "parentId": "4", "IsChecked": false, "children":[] }
] }]
},
{ "id": "2", "text": "Men", "parentId": null, "IsChecked": false,
"children": [{ "id": "10", "text": "Sweatshirts", "parentId": "2", "IsChecked": false, "children":[]}]
},
{"id": "3", "text": "Kids", "parentId": null, "IsChecked": true,
"children": [{ "id": "12", "text": "Toys", "parentId": "3", "IsChecked": false, "children":[] }]
}
];
console.log(filterChecked(treeData));
.as-console-wrapper { max-height: 100% !important; top: 0; }
use Lodash _.filter and _.every
_.filter(treedData, function(item) {
return _.every([
item.IsChecked,
_.every(item.children, 'IsChecked')
]);
});
if you also want to check condition of children of children you can do it recursively like
_.filter(treedData, function check(item) {
return _.every([
item.IsChecked,
_.size(item.children) === 0 || _.every(item.children, check)
]);
});

How can I read specific property from a JSON string in JavaScript?

How can I read agent_code from this string with JavaScript? And please explain me the logic.
JSON (one-line):
[{"name":"NYC","zone_id":"1","totalagents":"40","agents":[{"id":"1","agent_code":"====="},{"id":"2","agent_code":"====="},{"id":"3","agent_code":"Christian"},{"id":"4","agent_code":"Tom"},{"id":"5","agent_code":"Dave Damsky"},{"id":"6","agent_code":"====="},{"id":"7","agent_code":"Andrew"},{"id":"8","agent_code":"Paolo"},{"id":"9","agent_code":"Josh"},{"id":"10","agent_code":"Shipster Van"},{"id":"11","agent_code":"====="},{"id":"16","agent_code":"Christian2"},{"id":"20","agent_code":"Nathan"},{"id":"21","agent_code":"Aaron"},{"id":"22","agent_code":"Rob"},{"id":"23","agent_code":"Taylor"},{"id":"24","agent_code":"Drea"},{"id":"25","agent_code":"Mario "},{"id":"26","agent_code":"Julio"},{"id":"27","agent_code":"Abbas"},{"id":"28","agent_code":"Ahmed"},{"id":"29","agent_code":"David Damsky"},{"id":"30","agent_code":"Micheal"},{"id":"31","agent_code":"Moe"},{"id":"32","agent_code":"Luis"},{"id":"33","agent_code":"Darin"},{"id":"37","agent_code":"Alan"},{"id":"39","agent_code":"Cristian Marte"},{"id":"40","agent_code":"Cody"},{"id":"41","agent_code":"David Pinto"},{"id":"42","agent_code":"Will "},{"id":"44","agent_code":"Evan"},{"id":"45","agent_code":"Santiago"},{"id":"46","agent_code":"John"},{"id":"47","agent_code":"Moubeen"},{"id":"49","agent_code":"Devin Armstrong"},{"id":"50","agent_code":"Marco Bell"},{"id":"51","agent_code":"Youness Benzaid"},{"id":"52","agent_code":"Amin Mechouche"},{"id":"53","agent_code":"Franco Herrera"}]}]
JSON (formatted):
[
{
"name": "NYC",
"zone_id": "1",
"totalagents": "40",
"agents": [
{
"id": "1",
"agent_code": "====="
},
{
"id": "2",
"agent_code": "====="
},
{
"id": "3",
"agent_code": "Christian"
},
{
"id": "4",
"agent_code": "Tom"
},
{
"id": "5",
"agent_code": "Dave Damsky"
},
{
"id": "6",
"agent_code": "====="
},
{
"id": "7",
"agent_code": "Andrew"
},
{
"id": "8",
"agent_code": "Paolo"
},
{
"id": "9",
"agent_code": "Josh"
},
{
"id": "10",
"agent_code": "Shipster Van"
},
{
"id": "11",
"agent_code": "====="
},
{
"id": "16",
"agent_code": "Christian2"
},
{
"id": "20",
"agent_code": "Nathan"
},
{
"id": "21",
"agent_code": "Aaron"
},
{
"id": "22",
"agent_code": "Rob"
},
{
"id": "23",
"agent_code": "Taylor"
},
{
"id": "24",
"agent_code": "Drea"
},
{
"id": "25",
"agent_code": "Mario "
},
{
"id": "26",
"agent_code": "Julio"
},
{
"id": "27",
"agent_code": "Abbas"
},
{
"id": "28",
"agent_code": "Ahmed"
},
{
"id": "29",
"agent_code": "David Damsky"
},
{
"id": "30",
"agent_code": "Micheal"
},
{
"id": "31",
"agent_code": "Moe"
},
{
"id": "32",
"agent_code": "Luis"
},
{
"id": "33",
"agent_code": "Darin"
},
{
"id": "37",
"agent_code": "Alan"
},
{
"id": "39",
"agent_code": "Cristian Marte"
},
{
"id": "40",
"agent_code": "Cody"
},
{
"id": "41",
"agent_code": "David Pinto"
},
{
"id": "42",
"agent_code": "Will "
},
{
"id": "44",
"agent_code": "Evan"
},
{
"id": "45",
"agent_code": "Santiago"
},
{
"id": "46",
"agent_code": "John"
},
{
"id": "47",
"agent_code": "Moubeen"
},
{
"id": "49",
"agent_code": "Devin Armstrong"
},
{
"id": "50",
"agent_code": "Marco Bell"
},
{
"id": "51",
"agent_code": "Youness Benzaid"
},
{
"id": "52",
"agent_code": "Amin Mechouche"
},
{
"id": "53",
"agent_code": "Franco Herrera"
}
]
}
]
Lets say your above is a json string
var jsonString = '[{"name":"NYC","zone_id":"1","totalagents":"40","agents":[{"id":"1","agent_code":"====="},{"id":"2","agent_code":"====="},{"id":"3","agent_code":"Christian"},{"id":"4","agent_code":"Tom"},{"id":"5","agent_code":"Dave Damsky"},{"id":"6","agent_code":"====="},{"id":"7","agent_code":"Andrew"},{"id":"8","agent_code":"Paolo"},{"id":"9","agent_code":"Josh"},{"id":"10","agent_code":"Shipster Van"},{"id":"11","agent_code":"====="},{"id":"16","agent_code":"Christian2"},{"id":"20","agent_code":"Nathan"},{"id":"21","agent_code":"Aaron"},{"id":"22","agent_code":"Rob"},{"id":"23","agent_code":"Taylor"},{"id":"24","agent_code":"Drea"},{"id":"25","agent_code":"Mario "},{"id":"26","agent_code":"Julio"},{"id":"27","agent_code":"Abbas"},{"id":"28","agent_code":"Ahmed"},{"id":"29","agent_code":"David Damsky"},{"id":"30","agent_code":"Micheal"},{"id":"31","agent_code":"Moe"},{"id":"32","agent_code":"Luis"},{"id":"33","agent_code":"Darin"},{"id":"37","agent_code":"Alan"},{"id":"39","agent_code":"Cristian Marte"},{"id":"40","agent_code":"Cody"},{"id":"41","agent_code":"David Pinto"},{"id":"42","agent_code":"Will "},{"id":"44","agent_code":"Evan"},{"id":"45","agent_code":"Santiago"},{"id":"46","agent_code":"John"},{"id":"47","agent_code":"Moubeen"},{"id":"49","agent_code":"Devin Armstrong"},{"id":"50","agent_code":"Marco Bell"},{"id":"51","agent_code":"Youness Benzaid"},{"id":"52","agent_code":"Amin Mechouche"},{"id":"53","agent_code":"Franco Herrera"}]}]';
var json = JSON.parse(jsonString); // parse string into json
Now as this json is an array with length 1, to get all agent code you will have to do something like this.
for (var i = 0; i <json[0].agents.length; i++) {
console.log(json[0].agents[i].agent_code);
}

Categories