Related
I have a problem trying to build an array, then combine and output multiple objects depending on the id.
This is the problem (I hope it makes sense):
I am looping through multiple objects, then create an array depending on the value of the type of the object. I then take that array and build it into the object. Once that is done I need to run through all the objects and combine any that have the same id.
this is an example of how it would originally look:
[{
"id": "755",
"entities": ["14394551"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 43,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"],
"exchangerate": 1
}, {
"id": "755",
"entities": ["14394553"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 28,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
"exchangerate": 1
},{
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 38,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14434400"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 18,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14430895"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 63,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "Dep",
"salesOrderId": ["14430894"],
"memo": ["MICGB2452"],
"exchangerate": 1
}, {
"id": "762",
"entities": ["14350538"],
"accountID": "762",
"accountName": "122100 TEST1",
"amount": 45,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
"exchangerate": 1
}, {
"id": "760",
"entities": ["14350538"],
"accountID": "760",
"accountName": "122100 TEST2",
"amount": 49,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"],
"exchangerate": 1
}]
then this is after the array has been created -> Depending on the type.
[
{
"id": "755",
"accountID": "755",
"accountName": "122060 Test7",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14394551"],
"amount": 43,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"]
}],
"deposit": []
}, {
"id": "755",
"accountID": "755",
"accountName": "122060 Test7",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14394553"],
"amount": 28,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
}],
"deposit": []
},{
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14439896"],
"amount": 38,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"]
}],
"deposit": []
}, {
"id": "758",
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit" : [{
"entities": ["14434400"],
"amount": 18,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"]
}],
"deposit": []
}, {
"id": "758",
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "Dep",
"exchangerate": 1,
"customerDeposit": [],
"deposit": [{
"entities": ["14430895"],
"amount": 63,
"memo": ["MICGB2452"],
}]
}, {
"id": "762",
"accountID": "762",
"accountName": "122100 TEST1",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [
{
"entities": ["14350538"],
"amount": 45,
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
}
],
"deposit": []
}, {
"id": "760",
"accountID": "760",
"accountName": "122100 TEST2",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14350538"],
"amount": 49,
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"]
}],
"deposit": []
}]
then this would be what I want the final output to be - all the same id objects have the customerDeposit / deposit combined.
[
{
"id": "755",
"accountID": "755",
"accountName": "122060 Test7",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14394551"],
"amount": 43,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"]
}, {
"entities": ["14394553"],
"amount": 28,
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
}],
"deposit": []
}, {
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14439896"],
"amount": 38,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"]
}, {
"entities": ["14434400"],
"amount": 18,
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"]
}],
"deposit": [{
"entities": ["14430895"],
"amount": 63,
"memo": ["MICGB2452"],
}]
}, {
"id": "762",
"accountID": "762",
"accountName": "122100 TEST1",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [
{
"entities": ["14350538"],
"amount": 45,
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
}
],
"deposit": []
}, {
"id": "760",
"accountID": "760",
"accountName": "122100 TEST2",
"subsidiary": "2",
"currency": "1",
"type": "CustDep",
"exchangerate": 1,
"customerDeposit": [{
"entities": ["14350538"],
"amount": 49,
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"]
}],
"deposit": []
}]
This is my current code but it is not working as i want as it skips any ids that dont have more than one customerDeposit / deposit as it doesn't get into the if (objForId) statement.
function createDeposit(values) {
deposit = {
entities: values.entities,
amount: values.amount,
memo: values.memo,
};
return deposit;
}
function createCustomerDeposit(values) {
customerDeposit = {
entities: values.entities,
amount: values.amount,
memo: values.memo,
webPaymentMethod: values.webPaymentMethod,
webPaymentMethodID: values.webPaymentMethodID,
salesOrderId: values.salesOrderId,
};
return customerDeposit;
}
function run() {
const transferData = [{
"id": "755",
"entities": ["14394551"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 43,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394550"],
"memo": ["MAINGB588328"],
"exchangerate": 1
}, {
"id": "755",
"entities": ["14394553"],
"accountID": "755",
"accountName": "122060 Test7",
"amount": 28,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test7",
"webPaymentMethodID": "14",
"type": "CustDep",
"salesOrderId": ["14394552"],
"memo": ["MAINGB588333"],
"exchangerate": 1
},{
"id": "758",
"entities": ["14439896"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 38,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14439895"],
"memo": ["MICGB2454"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14434400"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 18,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "CustDep",
"salesOrderId": ["14434399"],
"memo": ["MICGB2453"],
"exchangerate": 1
}, {
"id": "758",
"entities": ["14430895"],
"accountID": "758",
"accountName": "122070 Test5",
"amount": 63,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "Test5",
"webPaymentMethodID": "12",
"type": "Dep",
"salesOrderId": ["14430894"],
"memo": ["MICGB2452"],
"exchangerate": 1
}, {
"id": "762",
"entities": ["14350538"],
"accountID": "762",
"accountName": "122100 TEST1",
"amount": 45,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST1",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14350537"],
"memo": ["MAINGB586991"],
"exchangerate": 1
}, {
"id": "760",
"entities": ["14350538"],
"accountID": "760",
"accountName": "122100 TEST2",
"amount": 49,
"subsidiary": "2",
"currency": "1",
"webPaymentMethod": "TEST2",
"webPaymentMethodID": "13",
"type": "CustDep",
"salesOrderId": ["14321538"],
"memo": ["MAINGB452756"],
"exchangerate": 1
}];
var customerDeposit = [];
var deposit = [];
var res = transferData.reduce(function (agg, obj) {
var objForId = agg.filter(function (idObj) {
return idObj.id === obj.id;
})[0];
if (objForId) {
if(obj.type === 'CustDep') {
objForId.customerDeposit.push(createCustomerDeposit(obj));
}
if(obj.type === 'Dep') {
objForId.deposit.push(createDeposit(obj));
}
} else {
agg.push({
id: obj.id,
accountID: obj.accountID,
accountName: obj.accountName,
subsidiary: obj.subsidiary,
currency: obj.currency,
exchangerate: obj.exchangerate,
customerDeposit,
deposit
});
customerDeposit = [];
deposit = [];
}
return agg;
}, []);
console.log(res);
}
run();
Any help would be really appreciated. Hopefully the question makes sense.
Thanks
I searched this a lot on stackoverflow before posting this ticket so please don't consider this as duplicate question.
I have scenario of an array with two items, I am pushing an object at index 1 but it's pushing same object on both indexes.
Extra Object
const extraObj = {
"item_id": "4",
"item_name": "Extra Patty",
"item_image": "placeholder_img.jpg",
"item_price": "3.00",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "extra"
};
Items Array
const itemsArr = [
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item"
},
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item",
}
];
itemsArr[1].extras = [extraObj];
// result
[
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item",
"extras": [
{
"item_id": "4",
"item_name": "Extra Patty",
"item_image": "placeholder_img.jpg",
"item_price": "3.00",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "extra"
}
]
},
{
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item",
"extras": [
{
"item_id": "4",
"item_name": "Extra Patty",
"item_image": "placeholder_img.jpg",
"item_price": "3.00",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "extra"
}
]
}
]
case SET_FOOD_EXTRAS:
const { itemId, extra, extraIndex, itemIndex } = action.payload;
const cloneItems = cloneDeep([...state.items]);
// cloneItems.splice(itemIndex, 0, { extras: [extra] });
cloneItems[itemIndex].extras = [extra];
return {
...state,
items: cloneItems,
summary: setSummary(state, cloneItems)
};
It depends on how you populate your itemsArr.
If you do something like:
const ob1 = {
"item_id": "3",
"category_id": "12",
"item_name": "Waffles",
"item_image": "item_081220170335.jpg",
"is_variant": "0",
"item_price": "7",
"currency_code": "USD",
"currency_symbol": "$",
"gst_fee": "0.00",
"item_quantity": "1",
"branch_id": "1",
"is_type": "item"
}
itemsArr.push(ob1);
itemsArr.push(ob1);
Then, both items in the array point to the same object so any modifications to one will be reflected on the other.
One solution is to make copies of the object:
itemsArr.push({...ob1});
itemsArr.push({..ob1});
I'm trying to create a text search where I can filter through the names from an api.
It should look something like this:
https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/part3.mp4
I'm able to fetch everything from the api successfully I'm just having a hard time creating a filter to search through the first names and last names.
My API looks like this:
https://www.hatchways.io/api/assessment/students
fetch(url).then((resp) => resp.json()).then(function(data) {
let students = data.students;
return students.map(function(student) {
let values = student.grades;
let firstNames = student.firstName;
var sum = 0;
for (var i = 0; i < values.length; i++) {
sum += parseInt(values[i], 10); //don't forget to add the base
}
var avg = sum / values.length;
let li = createNode('li'),
img = createNode('img'),
span = createNode('span');
img.src = student.pic;
span.innerHTML = `<b><li>${firstNames} ${student.lastName}</li></b>
<li>${student.company} </li>
<li>${student.email} </li>
<li>Average: ${avg}</li>`;
})
})
.catch(function(error) {
console.log(JSON.stringify(error));
})
First we fix your code so it runs and produces valid HTML (spans do not have LIs)
Use the first LI content to filter using a dynamic regular expression.
const data = JSON.parse(`{ "students": [ { "city": "Fushë-Muhurr", "company": "Yadel", "email": "iorton0#imdb.com", "firstName": "Ingaberg", "grades": [ "78", "100", "92", "86", "89", "88", "91", "87" ], "id": "1", "lastName": "Orton", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg", "skill": "Oracle" }, { "city": "Sanghan", "company": "Avamm", "email": "cboards1#weibo.com", "firstName": "Clarke", "grades": [ "75", "89", "95", "93", "99", "82", "89", "76" ], "id": "2", "lastName": "Boards", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasautreprehenderit.jpg", "skill": "Sports" }, { "city": "Kugesi", "company": "Skalith", "email": "lromanet2#wired.com", "firstName": "Laurens", "grades": [ "88", "90", "79", "82", "81", "99", "94", "73" ], "id": "3", "lastName": "Romanet", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/aspernaturnonsapiente.jpg", "skill": "Employee Handbooks" }, { "city": "Krajan", "company": "Mybuzz", "email": "bskitt3#aboutads.info", "firstName": "Berti", "grades": [ "88", "93", "92", "81", "95", "98", "77", "94" ], "id": "4", "lastName": "Skitt", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/autautdeserunt.jpg", "skill": "Nutrition Education" }, { "city": "Huiqi", "company": "Avavee", "email": "msummerley4#craigslist.org", "firstName": "Mureil", "grades": [ "71", "81", "72", "92", "79", "82", "91", "90" ], "id": "5", "lastName": "Summerley", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/consequaturdelectusquis.jpg", "skill": "ISO 14971" }, { "city": "Jianghong", "company": "Twinte", "email": "rcoryndon5#cargocollective.com", "firstName": "Robbyn", "grades": [ "97", "92", "72", "99", "92", "92", "79", "96" ], "id": "6", "lastName": "Coryndon", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/autautdeserunt.jpg", "skill": "Cinema 4D" }, { "city": "Sanxi", "company": "Buzzster", "email": "seykel6#examiner.com", "firstName": "Sheena", "grades": [ "74", "95", "75", "95", "85", "97", "88", "85" ], "id": "7", "lastName": "Eykel", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/utquamut.jpg", "skill": "Ulead VideoStudio" }, { "city": "Huancheng", "company": "Edgeblab", "email": "mewen7#ycombinator.com", "firstName": "Minnnie", "grades": [ "80", "100", "97", "78", "99", "99", "76", "85" ], "id": "8", "lastName": "Ewen", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/nesciuntrerumlibero.jpg", "skill": "Vulcan" }, { "city": "Luoxiong", "company": "Fadeo", "email": "riban8#hubpages.com", "firstName": "Rory", "grades": [ "70", "100", "75", "96", "83", "90", "94", "92" ], "id": "9", "lastName": "Iban", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/autemporroplaceat.jpg", "skill": "EE4" }, { "city": "Toulon", "company": "Yakidoo", "email": "lroxby9#cam.ac.uk", "firstName": "Lenna", "grades": [ "70", "99", "81", "83", "78", "95", "81", "76" ], "id": "10", "lastName": "Roxby", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/doloribusquitempora.jpg", "skill": "LPS" }, { "city": "Lazo", "company": "Photolist", "email": "rfitzalana#parallels.com", "firstName": "Rosalynd", "grades": [ "98", "93", "78", "87", "99", "89", "97", "81" ], "id": "11", "lastName": "FitzAlan", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/utquamut.jpg", "skill": "Geography" }, { "city": "Bichura", "company": "Babblestorm", "email": "srapellib#adobe.com", "firstName": "Stephanie", "grades": [ "83", "97", "70", "96", "75", "98", "90", "71" ], "id": "12", "lastName": "Rapelli", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/enimpariaturoptio.jpg", "skill": "Identity Management" }, { "city": "Chvalšiny", "company": "Mynte", "email": "mmacdirmidc#plala.or.jp", "firstName": "Maire", "grades": [ "87", "73", "85", "98", "73", "95", "75", "97" ], "id": "13", "lastName": "MacDirmid", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/aspernaturnonsapiente.jpg", "skill": "Outdoor Advertising" }, { "city": "Itaparica", "company": "Photospace", "email": "nshepherdd#desdev.cn", "firstName": "Nicoline", "grades": [ "90", "73", "88", "95", "71", "100", "80", "86" ], "id": "14", "lastName": "Shepherd", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/nonipsaet.jpg", "skill": "Amazon VPC" }, { "city": "Praia da Vitória", "company": "Vitz", "email": "ythornse#github.com", "firstName": "Yoshi", "grades": [ "78", "78", "96", "92", "80", "82", "91", "99" ], "id": "15", "lastName": "Thorns", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg", "skill": "DMR" }, { "city": "Sambir", "company": "Twitterwire", "email": "mtothef#shutterfly.com", "firstName": "Marna", "grades": [ "88", "74", "76", "89", "75", "97", "75", "86" ], "id": "16", "lastName": "Tothe", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/utquamut.jpg", "skill": "PFI" }, { "city": "Sarulla", "company": "Blogpad", "email": "okearyg#g.co", "firstName": "Orelia", "grades": [ "78", "92", "86", "80", "82", "95", "76", "84" ], "id": "17", "lastName": "Keary", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/enimpariaturoptio.jpg", "skill": "General Surgery" }, { "city": "Ochakovo-Matveyevskoye", "company": "Mydeo", "email": "mswaith#cafepress.com", "firstName": "Moses", "grades": [ "84", "82", "92", "74", "87", "98", "86", "73" ], "id": "18", "lastName": "Swait", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/velitnonquibusdam.jpg", "skill": "Sales Tax" }, { "city": "Youxi Chengguanzhen", "company": "Avaveo", "email": "fnusseyi#skyrock.com", "firstName": "Fonsie", "grades": [ "100", "75", "84", "91", "100", "97", "98", "87" ], "id": "19", "lastName": "Nussey", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/remtemporavelit.jpg", "skill": "Urbanism" }, { "city": "Limoges", "company": "Tazzy", "email": "srydingsj#phoca.cz", "firstName": "Skelly", "grades": [ "89", "81", "77", "93", "96", "96", "70", "79" ], "id": "20", "lastName": "Rydings", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/etporroalias.jpg", "skill": "IFTA" }, { "city": "Łobżenica", "company": "Quatz", "email": "obrennekek#yellowbook.com", "firstName": "Olly", "grades": [ "81", "74", "77", "82", "74", "88", "86", "87" ], "id": "21", "lastName": "Brenneke", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/velitnonquibusdam.jpg", "skill": "ATM Networks" }, { "city": "Divo", "company": "Gigazoom", "email": "nbadwickl#nifty.com", "firstName": "Norby", "grades": [ "73", "99", "91", "92", "85", "96", "95", "73" ], "id": "22", "lastName": "Badwick", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/delenitiestdolorum.jpg", "skill": "Media Relations" }, { "city": "Sortavala", "company": "Eamia", "email": "mmichiem#nifty.com", "firstName": "Melody", "grades": [ "100", "83", "76", "71", "93", "95", "73", "88" ], "id": "23", "lastName": "Michie", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/sitlaborecorrupti.jpg", "skill": "PC Games" }, { "city": "Taupo", "company": "Midel", "email": "jwillougheyn#psu.edu", "firstName": "Janice", "grades": [ "71", "80", "83", "99", "91", "95", "81", "75" ], "id": "24", "lastName": "Willoughey", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/dolordoloremassumenda.jpg", "skill": "Kondor+" }, { "city": "Krajandadapmulyo", "company": "Wikibox", "email": "ggallymoreo#mashable.com", "firstName": "Geraldine", "grades": [ "97", "71", "89", "85", "85", "87", "92", "75" ], "id": "25", "lastName": "Gallymore", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/sitlaborecorrupti.jpg", "skill": "WTL" } ] }`);
let students = data.students;
students.forEach(function(student) {
let values = student.grades;
let firstNames = student.firstName;
let sum = values.reduce((a,b) => +a + +b, 0); //convert to ints before summing
let avg = (sum / values.length).toFixed(2);
let card = document.createElement("div"), // wrapper
li = document.createElement('li'),
img = document.createElement('img'),
ul = document.createElement('ul');
ul.classList.add("filter");
img.src = student.pic;
ul.innerHTML = `<li><b>${firstNames} ${student.lastName}</b></li>
<li>${student.company} </li>
<li>${student.email} </li>
<li>Average: ${avg}</li>`;
card.appendChild(img);
card.appendChild(ul);
document.getElementById("container").appendChild(card)
})
document.getElementById("filter").addEventListener("input", (e) => {
let val = e.target.value;
re = new RegExp(val.split(" ").join("|"), "gi"); // creates /joe|blow/gi
document.querySelectorAll("ul.filter").forEach(ele => {
const words = ele.firstChild.textContent.split(' ');
let found = words.some(c => re.test(c));
ele.closest("div").style.display = found ? "" : "none"; // toggle the card
});
})
//Alternatives for the textContent:
// ul.setAttribute("data-filter", `${firstNames} ${student.lastName}`);
// `${firstNames} ${student.lastName}`.split(" ").forEach(name => ul.classList.add(name) )
ul {list-style: none}
#container img { float:left; padding:5px }
#filter { position:fixed; margin-left:300px }
<input id="filter" />
<div id="container"></div>
I have the following JSON:
{
"-KtDGS8GdOcJ33Lcqjok": {
"2017": {
"address": "test address 1",
"area2": "3212",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Solar",
"client": "Test Contact",
"createdAt": 1504551753483,
"lastEdited": 1504551805648,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.490362758827665",
"lng": "-69.93279173970221",
"name": "17002 - test",
"pictures": {
"a95ff256-0f05-3122-a6b5-a88d3fd14c3f": true
},
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "1234",
"year": "2017"
}
},
"-KtDGaU9BB6eNj-MsyBg": {
"2015": {
"address": "test 2a",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504552100747,
"lastEdited": 1504552100747,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "15002 - test2a ",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2015"
},
"2017": {
"address": "test 2",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504551790632,
"lastEdited": 1504551790632,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "17003 - test2b",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2017"
}
},
"codeCounter": {
"2015": 2,
"2017": 5
},
"totals": {
"2015": 1,
"2017": 5
}
}
It's basically a list of objects, each object contains one or more nested objects wrapped in the year they were made (physically these are houses,apartments, etc.).
Where I'm having trouble is trying to map the 'year' objects (2017, 2015, etc') as they may or may not exist. For example, an object may have both 2017, 2016 entries or only one of them, etc.
I already have a 'Property' model class that I believe works, it has all the address, author, category, etc. fields. I'm trying to create the outter class that would contain a list of these property objects:
export interface PropertyWrapper {
[year: number]: Property;
}
I tried parsing the JSON as a PropertyWrapper[] array and this way I can already access a property by calling:
for (const pw of data) {
console.log(pw[2017]);
}
But this only works because I already know the object has a '2017' entry. How could I do this dynamically regardless of whether or not there's a '2017', '2010', or 10 entries ?
Are you looking for something like this.
First gets object keys, then loop through these keys and then loop through nested object keys
var jso = {
"-KtDGS8GdOcJ33Lcqjok": {
"2017": {
"address": "test address 1",
"area2": "3212",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Solar",
"client": "Test Contact",
"createdAt": 1504551753483,
"lastEdited": 1504551805648,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.490362758827665",
"lng": "-69.93279173970221",
"name": "17002 - test",
"pictures": {
"a95ff256-0f05-3122-a6b5-a88d3fd14c3f": true
},
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "1234",
"year": "2017"
}
},
"-KtDGaU9BB6eNj-MsyBg": {
"2015": {
"address": "test 2a",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504552100747,
"lastEdited": 1504552100747,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "15002 - test2a ",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2015"
},
"2017": {
"address": "test 2",
"area1": "3245",
"author": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"category": "Local: comercio",
"client": "test2 ",
"createdAt": 1504551790632,
"lastEdited": 1504551790632,
"lastEditedBy": "STOkzlbT4OeOcbO2ed9Z7dvxZk92",
"lat": "18.489417118875462",
"level": "4",
"lng": "-69.92930956184864",
"name": "17003 - test2b",
"parking": "12",
"plaza": "Agora",
"price": "213",
"province": "-KtDBavhyLhrpV8hDuj2",
"restrooms": "2",
"sector": "-KtDBqgy3CqpTv6c_iQ9",
"totalPrice": "213",
"year": "2017"
}
},
"codeCounter": {
"2015": 2,
"2017": 5
},
"totals": {
"2015": 1,
"2017": 5
}
};
Object.keys(jso).forEach(function(key) {
Object.keys(jso[key]).forEach(function(nestedKey){
console.log(`nestedKey: ${nestedKey} \n ` , jso[key][nestedKey]);
});
});
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have function in my code that is presented below. So, while working I see a beautiful error...
Uncaught TypeError: Cannot read property 'length' of undefined
There is my code:
.on('slider', function (data) {
if(ngtimerStatus) {
ngtimerStatus = false;
$('.forceClose').addClass('msgs-not-visible');
console.log(data);
var users = data.users;
console.log(users);
users = mulAndShuffle(users, Math.ceil(110 / users.length));
users[6] = data.winner;
users[100] = data.winner;
html = '';
...
All in all I found that $data is nit empty!
It includes
{
"chance": 98.6,
"users": [
{
"updated_at": "2015-11-24 22:25:59",
"created_at": "2015-11-24 14:56:20",
"remember_token": "xespxJgYoYR9Pe1WQOYjMa3xuN4JYG708XJ20qhMJbMNfA2B1a5yMM8p5jnm",
"is_moderator": "0",
"is_admin": "0",
"votes": "0",
"id": "1",
"username": "dota2expert.ru",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/a8/a80a9f13fdbfcf02053b73f55a4a0e8596221137_full.jpg",
"steamid": "STEAM_0:1:-24976791",
"steamid64": "76561198031473286",
"trade_link": "https://steamcommunity.com/tradeoffer/new/?partner=71207558&token=LbivBnv-",
"accessToken": "LbivBnv-",
"money": "0.00"
},
{
"updated_at": "2015-11-24 22:28:27",
"created_at": "2015-11-24 22:26:27",
"remember_token": "ZPcNSqC3nGsiuLdWTKp3IzVuqhwmj1RUYADTIOIxCGLqjfSa6V8U14qTIhs4",
"is_moderator": "0",
"is_admin": "0",
"votes": "0",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"trade_link": "",
"accessToken": "",
"money": "275.00"
}
],
"tickets": "478986",
"ticket": 173512,
"round_number": "0.362248050305609551",
"winner": {
"updated_at": "2015-11-24 22:42:37",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": 4370,
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"game": {
"winner": {
"updated_at": "2015-11-24 22:42:37",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": 4370,
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"bets": [
{
"user": {
"updated_at": "2015-11-24 22:25:59",
"id": "1",
"username": "dota2expert.ru",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/a8/a80a9f13fdbfcf02053b73f55a4a0e8596221137_full.jpg",
"steamid": "STEAM_0:1:-24976791",
"steamid64": "76561198031473286",
"money": "0.00",
"votes": "0",
"created_at": "2015-11-24 14:56:20"
},
"updated_at": "2015-11-24 21:43:38",
"created_at": "2015-11-24 21:43:38",
"id": "5",
"user_id": "1",
"game_id": "2",
"items": "[{\"name\":\"Inscribed Crescent Bow\",\"market_hash_name\":\"Inscribed Crescent Bow\",\"classid\":\"503011467\",\"rarity\":\"mythical\",\"price\":\"62.85\"}]",
"itemsCount": "1",
"price": "62.85",
"from": "0",
"to": "6284"
},
{
"user": {
"updated_at": "2015-11-24 22:25:59",
"id": "1",
"username": "dota2expert.ru",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/a8/a80a9f13fdbfcf02053b73f55a4a0e8596221137_full.jpg",
"steamid": "STEAM_0:1:-24976791",
"steamid64": "76561198031473286",
"money": "0.00",
"votes": "0",
"created_at": "2015-11-24 14:56:20"
},
"updated_at": "2015-11-24 21:50:23",
"created_at": "2015-11-24 21:50:23",
"id": "6",
"user_id": "1",
"game_id": "2",
"items": "[{\"name\":\"Talon of the Scarlet Raven\",\"market_hash_name\":\"Talon of the Scarlet Raven\",\"classid\":\"217224920\",\"rarity\":\"uncommon\",\"price\":\"2.02\"}]",
"itemsCount": "1",
"price": "2.02",
"from": "6285",
"to": "6486"
},
{
"user": {
"updated_at": "2015-11-24 22:28:27",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": "275.00",
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"updated_at": "2015-11-24 22:28:18",
"created_at": "2015-11-24 22:28:18",
"id": "7",
"user_id": "7",
"game_id": "2",
"items": "[{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"}]",
"itemsCount": "1",
"price": "315.00",
"from": "6487",
"to": "37986"
},
{
"user": {
"updated_at": "2015-11-24 22:28:27",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": "275.00",
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"updated_at": "2015-11-24 22:28:19",
"created_at": "2015-11-24 22:28:19",
"id": "8",
"user_id": "7",
"game_id": "2",
"items": "[{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"}]",
"itemsCount": "1",
"price": "315.00",
"from": "37987",
"to": "69486"
},
{
"user": {
"updated_at": "2015-11-24 22:28:27",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": "275.00",
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"updated_at": "2015-11-24 22:28:21",
"created_at": "2015-11-24 22:28:21",
"id": "9",
"user_id": "7",
"game_id": "2",
"items": "[{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"}]",
"itemsCount": "1",
"price": "315.00",
"from": "69487",
"to": "100986"
},
{
"user": {
"updated_at": "2015-11-24 22:28:27",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": "275.00",
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"updated_at": "2015-11-24 22:28:25",
"created_at": "2015-11-24 22:28:25",
"id": "10",
"user_id": "7",
"game_id": "2",
"items": "[{\"id\":\"4\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 3150 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_4.png\",\"price\":\"3150.00\"}]",
"itemsCount": "1",
"price": "3150.00",
"from": "100987",
"to": "415986"
},
{
"user": {
"updated_at": "2015-11-24 22:28:27",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": "275.00",
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"updated_at": "2015-11-24 22:28:26",
"created_at": "2015-11-24 22:28:26",
"id": "11",
"user_id": "7",
"game_id": "2",
"items": "[{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"}]",
"itemsCount": "1",
"price": "315.00",
"from": "415987",
"to": "447486"
},
{
"user": {
"updated_at": "2015-11-24 22:28:27",
"id": "7",
"username": "SKONIKS",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/d4/d4174b5213f60fc9612229320d633d421b373080_full.jpg",
"steamid": "STEAM_0:0:-4181615",
"steamid64": "76561198073063637",
"money": "275.00",
"votes": "0",
"created_at": "2015-11-24 22:26:27"
},
"updated_at": "2015-11-24 22:28:27",
"created_at": "2015-11-24 22:28:27",
"id": "12",
"user_id": "7",
"game_id": "2",
"items": "[{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"}]",
"itemsCount": "1",
"price": "315.00",
"from": "447487",
"to": "478986"
}
],
"updated_at": "2015-11-24 22:42:37",
"created_at": "2015-11-24 21:18:41",
"rand_number": "0.362248050305609551",
"status_prize": "0",
"id": "2",
"winner_id": "7",
"status": 3,
"items": "8",
"price": "4789.87",
"started_at": "2015-11-24 22:28:27",
"finished_at": {
"timezone": "Europe/Moscow",
"timezone_type": 3,
"date": "2015-11-24 22:42:37"
},
"won_items": "\n [{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"},\n {\"id\":\"4\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 3150 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_4.png\",\"price\":\"3150.00\"},{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"},{\"id\":\"1\",\"name\":\"\\u041a\\u0430\\u0440\\u0442\\u043e\\u0447\\u043a\\u0430 \\u043d\\u0430 315 \\u0440\\u0443\\u0431\",\"img\":\"assets\\/img\\/tickets\\/card_1.png\",\"price\":\"315.00\"}]"
}
}
where you can simply found part named "users" but data.users is empty! (underfined). Can you help me with it?
You might need to use data = JSON.parse(data);, before accessing data.users? It's hard to tell from your example.