Related
I tried to display products to a screen and what i get is that error,here is my code:
{productsCtg.length > 0 ? (
<View style={styles.listContainer}>
{productsCtg.map((item) => {
console.log(item);
return(
<ProductList
navigation={props.navigation}
key={item.id}
item={item}
/>
);
})}
</View>
) : (
<View style={[styles.center, { height: height / 2}]}>
<Text style={{fontFamily: 'nunito_semi_bold'}}>No products found</Text>
</View>
)}
And i fetch data from an api using useFocusEffect and useCallBack and axios,when app starts products shows but when i try to save any file in the project without making any changes that error appears and when i save again products show up again, i need help and here is another codes:
const [products, setProducts] = useState([]);
const [productsFiltered, setProductsFiltered] = useState([]);
const [focus, setFocus] = useState();
const [categories, setCategories] = useState([]);
const [productsCtg, setProductsCtg] = useState([]);
const [active, setActive] = useState();
const [initialState, setInitialState] = useState([]);
const [loading, setLoading] = useState(true)
useFocusEffect((
useCallback(
() => {
setFocus(false);
setActive(-1);
// Products
axios
.get(`${baseURL}products`)
.then((res) => {
setProducts(res.data);
setProductsFiltered(res.data);
setProductsCtg(res.data);
setInitialState(res.data);
setLoading(false);
//console.log(res.data)
})
.catch((error) => {
console.log('Api call error')
})
//Categories
axios
.get(`${baseURL}categories`)
.then((res) => {
setCategories(res.data);
//console.log(res.data);
})
.catch((error) => {
console.log('Api call error')
})
return () => {
setProducts([]);
setProductsFiltered([]);
setFocus();
setCategories([]);
setActive();
setInitialState();
// setProductsCtg([]);
};
},
[],
)
))
when i console.log before return() the first five arrays are empty and the rest contains repeated data, each array contains six products(objects),and and when i console.log inside a map function all the arrays have repeated data like below(but all),the output of console.log is:
Array []
Array []
Array []
Array []
Array []
Array [
Object {
"brand": "Arusha",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 45,
"dateCreated": "2022-06-04T06:32:06.300Z",
"description": "Mtama mzuri sana kutoka arusha",
"id": "629afc66e400878b161e437b",
"image": "http://2fa0-197-250-230-
109.eu.ngrok.io/public/uploads/21fe5b14-3eee-4218-b554-9a3d17bd801b.jpg-
1654333522641.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Mtama",
"numReviews": 0,
"price": 42000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Dodoma",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 27,
"dateCreated": "2022-06-04T08:59:36.678Z",
"description": "Good quality maize in Dodoma,place your order now.",
"id": "629b1ef89e9b9401aba2ba54",
"image": "http://2fa0-197-250-230-
109.eu.ngrok.io/public/uploads/fffe96ff-4558-42db-a6b4-7b5b289995be.jpg-
1654333175940.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Maize",
"numReviews": 0,
"price": 76000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Mbeya",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 16,
"dateCreated": "2022-06-05T10:04:19.040Z",
"description": "Mchele mzuri kutoka mbeya,weka oda yako sasa",
"id": "629c7fa3342fe22635019648",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/8c107f75-31e0-4a6c-9835-27a8f6ada063.jpg-
1654423458901.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Rice",
"numReviews": 0,
"price": 80000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Tanga",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 12,
"dateCreated": "2022-06-05T10:39:52.196Z",
"description": "Quality beans available,place your order anytime",
"id": "629c87f8499c526723a96979",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/291ee0f1-369e-45a1-8b43-38756c0d866b.jpg-
1654425591386.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Beans",
"numReviews": 0,
"price": 85000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Kilimanjaro",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 12,
"dateCreated": "2022-06-05T10:43:04.778Z",
"description": "Karibu upate ndizi kubwa na zenye ubora wa hali ya
juu,weka oda yako sasa",
"id": "629c88b8499c526723a9698c",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/4e10f2a7-9ee0-4735-bd8b-75b1af2d48e4.jpg-
1654425784444.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Ndizi",
"numReviews": 0,
"price": 31500,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Dar es salaam",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 133,
"dateCreated": "2022-06-05T10:47:48.391Z",
"description": "Tunauza mahindi kwa jumla,weka oda yako mapema,karibu
sana",
"id": "629c89d4499c526723a969a5",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/6895e399-6254-4c46-a757-2d10a0b188b2.jpg-
1654426067682.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Maize",
"numReviews": 0,
"price": 73500,
"rating": 0,
"richDescription": "undefined",
},
]
Array [
Object {
"brand": "Arusha",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 45,
"dateCreated": "2022-06-04T06:32:06.300Z",
"description": "Mtama mzuri sana kutoka arusha",
"id": "629afc66e400878b161e437b",
"image": "http://2fa0-197-250-230-
109.eu.ngrok.io/public/uploads/21fe5b14-3eee-4218-b554-9a3d17bd801b.jpg-
1654333522641.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Mtama",
"numReviews": 0,
"price": 42000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Dodoma",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 27,
"dateCreated": "2022-06-04T08:59:36.678Z",
"description": "Good quality maize in Dodoma,place your order now.",
"id": "629b1ef89e9b9401aba2ba54",
"image": "http://2fa0-197-250-230-
109.eu.ngrok.io/public/uploads/fffe96ff-4558-42db-a6b4-7b5b289995be.jpg-
1654333175940.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Maize",
"numReviews": 0,
"price": 76000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Mbeya",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 16,
"dateCreated": "2022-06-05T10:04:19.040Z",
"description": "Mchele mzuri kutoka mbeya,weka oda yako sasa",
"id": "629c7fa3342fe22635019648",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/8c107f75-31e0-4a6c-9835-27a8f6ada063.jpg-
1654423458901.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Rice",
"numReviews": 0,
"price": 80000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Tanga",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 12,
"dateCreated": "2022-06-05T10:39:52.196Z",
"description": "Quality beans available,place your order anytime",
"id": "629c87f8499c526723a96979",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/291ee0f1-369e-45a1-8b43-38756c0d866b.jpg-
1654425591386.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Beans",
"numReviews": 0,
"price": 85000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Kilimanjaro",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 12,
"dateCreated": "2022-06-05T10:43:04.778Z",
"description": "Karibu upate ndizi kubwa na zenye ubora wa hali ya
juu,weka oda yako sasa",
"id": "629c88b8499c526723a9698c",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/4e10f2a7-9ee0-4735-bd8b-75b1af2d48e4.jpg-
1654425784444.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Ndizi",
"numReviews": 0,
"price": 31500,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Dar es salaam",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 133,
"dateCreated": "2022-06-05T10:47:48.391Z",
"description": "Tunauza mahindi kwa jumla,weka oda yako mapema,karibu
sana",
"id": "629c89d4499c526723a969a5",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/6895e399-6254-4c46-a757-2d10a0b188b2.jpg-
1654426067682.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Maize",
"numReviews": 0,
"price": 73500,
"rating": 0,
"richDescription": "undefined",
},
]
Array [
Object {
"brand": "Arusha",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 45,
"dateCreated": "2022-06-04T06:32:06.300Z",
"description": "Mtama mzuri sana kutoka arusha",
"id": "629afc66e400878b161e437b",
"image": "http://2fa0-197-250-230-
109.eu.ngrok.io/public/uploads/21fe5b14-3eee-4218-b554-9a3d17bd801b.jpg-
1654333522641.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Mtama",
"numReviews": 0,
"price": 42000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Dodoma",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 27,
"dateCreated": "2022-06-04T08:59:36.678Z",
"description": "Good quality maize in Dodoma,place your order now.",
"id": "629b1ef89e9b9401aba2ba54",
"image": "http://2fa0-197-250-230-
109.eu.ngrok.io/public/uploads/fffe96ff-4558-42db-a6b4-7b5b289995be.jpg-
1654333175940.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Maize",
"numReviews": 0,
"price": 76000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Mbeya",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 16,
"dateCreated": "2022-06-05T10:04:19.040Z",
"description": "Mchele mzuri kutoka mbeya,weka oda yako sasa",
"id": "629c7fa3342fe22635019648",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/8c107f75-31e0-4a6c-9835-27a8f6ada063.jpg-
1654423458901.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Rice",
"numReviews": 0,
"price": 80000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Tanga",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 12,
"dateCreated": "2022-06-05T10:39:52.196Z",
"description": "Quality beans available,place your order anytime",
"id": "629c87f8499c526723a96979",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/291ee0f1-369e-45a1-8b43-38756c0d866b.jpg-
1654425591386.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Beans",
"numReviews": 0,
"price": 85000,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Kilimanjaro",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 12,
"dateCreated": "2022-06-05T10:43:04.778Z",
"description": "Karibu upate ndizi kubwa na zenye ubora wa hali ya
juu,weka oda yako sasa",
"id": "629c88b8499c526723a9698c",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/4e10f2a7-9ee0-4735-bd8b-75b1af2d48e4.jpg-
1654425784444.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Ndizi",
"numReviews": 0,
"price": 31500,
"rating": 0,
"richDescription": "undefined",
},
Object {
"brand": "Dar es salaam",
"category": Object {
"__v": 0,
"_id": "62925a7db9e8b1361367c733",
"color": null,
"icon": null,
"name": "food crops",
},
"countInStock": 133,
"dateCreated": "2022-06-05T10:47:48.391Z",
"description": "Tunauza mahindi kwa jumla,weka oda yako mapema,karibu
sana",
"id": "629c89d4499c526723a969a5",
"image": "http://1063-197-250-224-
205.eu.ngrok.io/public/uploads/6895e399-6254-4c46-a757-2d10a0b188b2.jpg-
1654426067682.jpeg",
"images": Array [],
"isFeatured": false,
"name": "Maize",
"numReviews": 0,
"price": 73500,
"rating": 0,
"richDescription": "undefined",
},
]
check type of productsCtg if it is Object;
This error means productsCtg is not a array
Try:
console.log(productsCtg)
I'm filtering a list using a const queryModifier = {price: "lessThan", weight: "greaterThan"}
const queryKeys = keys: {
price: '1000',
weight: '1000'
}
const list = [
{
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-11-05 10:48:18",
"createdBy": "test#test.com",
"deliveryDate": "2019-11-08 10:46:37",
"driver": "",
"dropOff": "Kögel Trailer GmbH & Co. KG, Am Kögel-Werk, Burtenbach, Germany",
"height": 0,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "7e249529-d089-47bb-b0ad-470f850dd8cf",
"notes": "",
"orderId": "",
"pickUp": "Altenberge, Germany",
"price": 500,
"quantity": 1,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "engl. Anschlüsse",
"vehicleId": "505123",
"vehicleReadyDate": "2019-11-05 10:47:57",
"weight": 0
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-10-14 16:32:12",
"createdBy": "test#test.com",
"deliveryDate": "2019-10-19 16:26:35",
"driver": "",
"dropOff": "Marville-Moutiers-Brûlé, France",
"height": 600,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "9b7f57fd-f95e-4038-b120-a0301fdf3f31",
"notes": "",
"orderId": "",
"pickUp": "Altenberge, Germany",
"price": 0,
"quantity": 1,
"trailer": "2er Pack",
"vehicle": "Anhänger",
"vehicleClass": "50",
"vehicleId": "123",
"vehicleReadyDate": "2019-10-16 16:31:26",
"weight": 12000
},
{
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-10-14 16:25:54",
"createdBy": "test#test.com",
"deliveryDate": "2019-10-19 16:24:13",
"driver": "",
"dropOff": "Vendenheim, France",
"height": 0,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "7e4f233f-695b-40eb-a0ca-fd78f3fa43cd",
"notes": "",
"orderId": "",
"pickUp": "Altenberge, Germany",
"price": 793,
"quantity": 1,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "Standard",
"vehicleId": "3340731",
"vehicleReadyDate": "2019-10-15 16:24:58",
"weight": 0
},
{
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-26 18:32:18",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-20 18:31:45",
"driver": "Michal Kucharski",
"dropOff": "Logroño, Spain",
"height": 0,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "388113f5-3927-4fe3-80d5-f2fcf1c7cedd",
"notes": "",
"orderId": "",
"pickUp": "16671 Butano Place, Fontana, CA, USA",
"price": 0,
"quantity": 1,
"trailer": "2er Pack",
"vehicle": "Sattel",
"vehicleClass": "Standard",
"vehicleId": "efgefg",
"vehicleReadyDate": "2019-09-27 18:32:08",
"weight": 0
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-06 22:57:55",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-07 22:57:03",
"driver": "Eugeniusz Galinski",
"dropOff": "12345 Lamplight Village Avenue, Austin, TX, USA",
"height": 32,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "ac3cf14e-b43b-45e4-9168-ad4997b6415d",
"notes": "Nzube I am adding notes here",
"pickUp": "16671 Butano Place, Fontana, CA, USA",
"price": 100,
"quantity": 3,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "Mega",
"vehicleId": "123",
"vehicleReadyDate": "2019-09-26 22:57:36",
"weight": 12
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-06 22:46:25",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-06 22:45:45",
"driver": "Michal Kucharski",
"dropOff": "QEW, Niagara Falls, ON, Canada",
"height": 67,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "d0ec3b82-2279-4d11-8e35-a9307713ae5a",
"notes": "This is coming along",
"pickUp": "Avenida Callao 1234, Buenos Aires, Argentina",
"price": 100,
"quantity": 1,
"trailer": "2er Pack",
"vehicle": "Sattel",
"vehicleClass": "Mega",
"vehicleId": "123",
"vehicleReadyDate": "2019-09-25 22:45:57",
"weight": 12
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-04 18:06:18",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-05 18:05:51",
"driver": "Chibuzo ilogu",
"dropOff": "Asda Park Royal Superstore, Western Road, London, UK",
"height": 453,
"isPreparingTrailer": true,
"isSmsSent": true,
"isTrailerReady": true,
"key": "96ee9410-4d70-4bbc-8016-5d7c9e5ecec1",
"notes": "ewriupoi ",
"pickUp": "Avenida Juan Bautista Alberdi 1233, Buenos Aires, Argentina",
"price": 234,
"quantity": 1,
"trailer": "3er Pack",
"vehicle": "Anhänger",
"vehicleClass": "50",
"vehicleId": "543",
"vehicleReadyDate": "2019-09-21 18:06:03",
"weight": 453
},
{
"additionalPrices": 0,
"companyName": "Test Company",
"completeDate": "2019-09-04 18:02:27",
"createdAt": "2019-09-04 18:01:30",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-04 18:01:09",
"driver": "Chibuzo ilogu",
"dropOff": "La Cabaña 123, Las Condes, Chile",
"height": 123,
"isPreparingTrailer": false,
"isSmsSent": true,
"isTrailerReady": true,
"key": "bcd50f43-0644-49a7-8bdc-009a4572341b",
"notes": "qewqe",
"pickUp": "La Cabaña 123, Las Condes, Chile",
"price": 123,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "Standard",
"vehicleId": "123",
"vehicleReadyDate": "2019-10-02 18:01:19",
"weight": 123
}
];
export const handleFilterModifier = (value, compareValue, modifier) => {
if (modifier === 'lessThan') {
return value > compareValue;
}
if (modifier === 'equals') {
return value === compareValue;
}
if (modifier === 'greaterThan') {
return value < compareValue;
}
return null;
};
const resultList = list.filter(
item => Object.entries(queryModifiers).every(([filterKey, filterVal]) => {
const compareValue = item[filterKey];
const value = Object.values(queryKeys);
const result = handleFilterModifier(
parseFloat(value),
compareValue,
filterVal
);
return result;
})
);
This operation fails when either of the queryModifiers has "equals" in its value pair. Anything else returns the actual true result. I don't understand why it fails on "equals".
I feel like there should be a forEach somewhere but I don't know where to put it and maybe there's something wrong with the code. I need help figuring it out.
I think you should replace this
const queryKeys = keys: {
price: '1000',
weight: '1000'
}
with
const queryKeys = {
price: '1000',
weight: '1000'
}
and replace this
const value = Object.values(queryKeys);
with
const value = queryKeys[filterKey];
I'm trying to output all of the customer id's within my JSON data. I am using ejs as my templating engine. So far I'm only able to succsefully output 1 customer id via:
<p><%= jsonOrderData.orders[0].customer.id %></p>
When I try to loop through each order I get Cannot read property 'id' of undefined
for loop to loop through
<% for (var i = 0; i < jsonOrderData.orders.length; i++) {%>
<p>Customer: <%= jsonOrderData.orders[i].customer.id %></p>
<% }; %>
If I remove the .id after customer the error then goes away. It then outputs
Customer:[object Object] 50 times which is the legth of the json data.
I don't understand why it's not working within the loop when adding .id when it works fine without the loop manually setting the index?
JSON DATA (Cut Down 2 Orders)
{
"orders": [
{
"id": 533078016054,
"email": "email#gmail.com",
"closed_at": null,
"created_at": "2018-08-10T05:03:36+01:00",
"updated_at": "2018-08-10T05:03:37+01:00",
"number": 52,
"note": "",
"token": "f4877048c08eb98180ee5fda34f978bc",
"gateway": "manual",
"test": false,
"total_price": "13.98",
"subtotal_price": "13.98",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "13.98",
"cart_token": null,
"buyer_accepts_marketing": false,
"name": "#MW1052",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "18.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": null,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-10T05:03:36+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1052,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "email#gmail.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/f4877048c08eb98180ee5fda34f978bc/authenticate?key=redacted",
"admin_graphql_api_id": "gid://shopify/Order/redacted",
"line_items": [
{
"id": 1350736445494,
"variant_id": 8725905539126,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss15",
"variant_title": "S / Bottle Green",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Bottle Green",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736445494",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
},
{
"id": 1350736478262,
"variant_id": 8725905440822,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss12",
"variant_title": "S / Heather Grey",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Heather Grey",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736478262",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"billing_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "Jogn Doe",
"country_code": "GB",
"province_code": null
},
"shipping_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "John Doe",
"country_code": "GB",
"province_code": null
},
"fulfillments": [],
"refunds": [],
"customer": {
"id": 556974014518,
"email": "email#gmail.com",
"accepts_marketing": false,
"created_at": "2018-06-26T00:26:55+01:00",
"updated_at": "2018-08-10T05:03:36+01:00",
"first_name": "John",
"last_name": "Doe",
"orders_count": 22,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 533078016054,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "",
"last_order_name": "#MW1052",
"admin_graphql_api_id": "gid://shopify/Customer/556974014518",
"default_address": {
"id": 601657278518,
"customer_id": 556974014518,
"first_name": "John",
"last_name": "Doe",
"company": null,
"address1": "17A Oaklands Business Centre",
"address2": "Elm Grove",
"city": "Worthing",
"province": null,
"country": "United Kingdom",
"zip": "BN11 5LH",
"phone": null,
"name": "John Doe",
"province_code": null,
"country_code": "GB",
"country_name": "United Kingdom",
"default": true
}
}
},
{
"id": 532977778742,
"email": "james#bungeedesign.com",
"closed_at": null,
"created_at": "2018-08-09T22:18:53+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"number": 51,
"note": "",
"token": "a292d75bd7011cf255a1bf236b23d0a5",
"gateway": "manual",
"test": false,
"total_price": "6.99",
"subtotal_price": "6.99",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "6.99",
"cart_token": null,
"buyer_accepts_marketing": true,
"name": "#MW1051",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "9.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": 1327759385,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-09T22:18:53+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1051,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "james#bungeedesign.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/a292d75bd7011cf255a1bf236b23d0a5/authenticate?key=9322877ce6ce34be2feeb127d73d0f89",
"admin_graphql_api_id": "gid://shopify/Order/532977778742",
"line_items": [
{
"id": 1350552453174,
"variant_id": 8725905408054,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss11",
"variant_title": "S / Black",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Black",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350552453174",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"fulfillments": [],
"refunds": [],
"customer": {
"id": 552537620534,
"email": "james#bungeedesign.com",
"accepts_marketing": true,
"created_at": "2018-06-15T10:44:13+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"first_name": "James",
"last_name": "Rogers",
"orders_count": 18,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 532977778742,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "password page, prospect",
"last_order_name": "#MW1051",
"admin_graphql_api_id": "gid://shopify/Customer/552537620534"
}
}
]
}
What you have runs fine. It might be possible that something is getting lost in translation or .id is at another level. My guess is that you are not setting the variable jsonOrderData as you are expecting.
If you do console.log(jsonOrderData); do you get what you expect?
This works fine:
const json = {
"orders": [
{
"id": 533078016054,
"email": "email#gmail.com",
"closed_at": null,
"created_at": "2018-08-10T05:03:36+01:00",
"updated_at": "2018-08-10T05:03:37+01:00",
"number": 52,
"note": "",
"token": "f4877048c08eb98180ee5fda34f978bc",
"gateway": "manual",
"test": false,
"total_price": "13.98",
"subtotal_price": "13.98",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "13.98",
"cart_token": null,
"buyer_accepts_marketing": false,
"name": "#MW1052",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "18.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": null,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-10T05:03:36+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1052,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "email#gmail.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/f4877048c08eb98180ee5fda34f978bc/authenticate?key=redacted",
"admin_graphql_api_id": "gid://shopify/Order/redacted",
"line_items": [
{
"id": 1350736445494,
"variant_id": 8725905539126,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss15",
"variant_title": "S / Bottle Green",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Bottle Green",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736445494",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
},
{
"id": 1350736478262,
"variant_id": 8725905440822,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss12",
"variant_title": "S / Heather Grey",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Heather Grey",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736478262",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"billing_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "Jogn Doe",
"country_code": "GB",
"province_code": null
},
"shipping_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "John Doe",
"country_code": "GB",
"province_code": null
},
"fulfillments": [],
"refunds": [],
"customer": {
"id": 556974014518,
"email": "email#gmail.com",
"accepts_marketing": false,
"created_at": "2018-06-26T00:26:55+01:00",
"updated_at": "2018-08-10T05:03:36+01:00",
"first_name": "John",
"last_name": "Doe",
"orders_count": 22,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 533078016054,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "",
"last_order_name": "#MW1052",
"admin_graphql_api_id": "gid://shopify/Customer/556974014518",
"default_address": {
"id": 601657278518,
"customer_id": 556974014518,
"first_name": "John",
"last_name": "Doe",
"company": null,
"address1": "17A Oaklands Business Centre",
"address2": "Elm Grove",
"city": "Worthing",
"province": null,
"country": "United Kingdom",
"zip": "BN11 5LH",
"phone": null,
"name": "John Doe",
"province_code": null,
"country_code": "GB",
"country_name": "United Kingdom",
"default": true
}
}
},
{
"id": 532977778742,
"email": "james#bungeedesign.com",
"closed_at": null,
"created_at": "2018-08-09T22:18:53+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"number": 51,
"note": "",
"token": "a292d75bd7011cf255a1bf236b23d0a5",
"gateway": "manual",
"test": false,
"total_price": "6.99",
"subtotal_price": "6.99",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "6.99",
"cart_token": null,
"buyer_accepts_marketing": true,
"name": "#MW1051",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "9.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": 1327759385,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-09T22:18:53+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1051,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "james#bungeedesign.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/a292d75bd7011cf255a1bf236b23d0a5/authenticate?key=9322877ce6ce34be2feeb127d73d0f89",
"admin_graphql_api_id": "gid://shopify/Order/532977778742",
"line_items": [
{
"id": 1350552453174,
"variant_id": 8725905408054,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss11",
"variant_title": "S / Black",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Black",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350552453174",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"fulfillments": [],
"refunds": [],
"customer": {
"id": 552537620534,
"email": "james#bungeedesign.com",
"accepts_marketing": true,
"created_at": "2018-06-15T10:44:13+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"first_name": "James",
"last_name": "Rogers",
"orders_count": 18,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 532977778742,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "password page, prospect",
"last_order_name": "#MW1051",
"admin_graphql_api_id": "gid://shopify/Customer/552537620534"
}
}
]
};
for (let i = 0; i < json.orders.length; i++) {
const order = json.orders[i];
console.log(order.customer.id);
}
I cannot seem to extract the data I want from this (verified) JSON string coming from my home automation server (i.e. I cannot change the JSON return).
var myJson = '{ "Device_Num_6": { "states": [ { "id": 207, "service": "urn:upnp-org:serviceId:SwitchPower1", "variable": "Status", "value": "0" }, { "id": 208, "service": "urn:upnp-org:serviceId:Dimming1", "variable": "LoadLevelTarget", "value": "94" }, { "id": 209, "service": "urn:upnp-org:serviceId:Dimming1", "variable": "LoadLevelStatus", "value": "0" }, { "id": 210, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "Configured", "value": "1" }, { "id": 211, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "ModeSetting", "value": "1:;2:;3:;4:" }, { "id": 212, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "LastUpdate", "value": "1438440091" }, { "id": 213, "service": "urn:micasaverde-com:serviceId:HaDevice1", "variable": "FirstConfigured", "value": "1438440091" }, { "id": 214, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "Capabilities", "value": "209,140,0,4,17,1,L,R,RS,|38:1,39,112,114,115,134," }, { "id": 215, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "ManufacturerInfo", "value": "99,17495,12848" }, { "id": 216, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "VersionInfo", "value": "6,1,91,2,11" }, { "id": 217, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "NodeInfo", "value": "26,27,70,72,73,86," }, { "id": 218, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "Neighbors", "value": "1,2,3,4,6,7,8,9,11,12,13,14,15,16,17,21,25,26,27,31,32,33,34,35," }, { "id": 219, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastReset", "value": "0" }, { "id": 220, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "AssociationNum", "value": "0" }, { "id": 221, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastRouteUpdate", "value": "1468760253" }, { "id": 222, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "PollOk", "value": "43947" }, { "id": 223, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastNnu", "value": "1468735200,700" }, { "id": 224, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "LastArr", "value": "1468735200,700" }, { "id": 225, "service": "urn:micasaverde-com:serviceId:ZWaveDevice1", "variable": "PollNoReply", "value": "54" }, { "id": 226, "service": "urn:micasaverde-com:serviceId:ZWaveNetwork1", "variable": "ConsecutivePollFails", "value": "0" } ], "Jobs": [ ], "PendingJobs": 0, "tooltip": { "display": 0 }, "status": -1 }, "Using_2G": 0, "LoadTime": 1468766261, "DataVersion": 766262647, "UserData_DataVersion": 766261013, "TimeStamp": 1468779944, "lights_on": 3, "lights_off": 8, "doors_locked": 5, "doors_unlocked": 2, "sensors_tripped": 0, "sensors_not_tripped": 8, "failed_devices": 8, "visible_devices": 93, "partitions_active": 0, "partitions_notactive": 2, "alerts": [ { "PK_Device": 154, "Room": 10, "DeviceName": "Laundry Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742240051", "LocalDate": "2016-07-17 10:38:22", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766302, "Code": "SL_BATTERYALARM", "NewValue": "0", "Description": "Laundry Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 150, "Room": 23, "DeviceName": "Kids Bath Motion", "DeviceType": "urn:schemas-micasaverde-com:device:MotionSensor:1", "PK_Alert": "4742240181", "LocalDate": "2016-07-17 10:38:22", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766302, "Code": "SL_BATTERYALARM", "NewValue": "10", "Description": "Kids Bath Motion", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255081", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766418, "Code": "DL_LOW_BATTERY", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255231", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_LOCK_CHANGED", "NewValue": "3", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255371", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_CODE_CHANGED", "NewValue": "3", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255471", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_USERCODE", "NewValue": "UserID=\"1\" UserName=\"Main\"", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255591", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 3, "LocalTimestamp": 1468766418, "Code": "DL_LOCK_BUTTON", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255721", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 1, "LocalTimestamp": 1468766418, "Code": "DL_LOCK_FAILURE", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255801", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 1, "LocalTimestamp": 1468766418, "Code": "DL_PINFAILED", "NewValue": "1", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" }, { "PK_Device": 101, "Room": 21, "DeviceName": "Cabana Door Lock", "DeviceType": "urn:schemas-micasaverde-com:device:DoorLock:1", "PK_Alert": "4742255971", "LocalDate": "2016-07-17 10:40:18", "EventType": 4, "SourceType": 4, "Argument": 0, "Filesize": 0, "Severity": 2, "LocalTimestamp": 1468766418, "Code": "SL_BATTERYALARM", "NewValue": "0", "Description": "Cabana Door Lock", "Users": "", "Server_Storage": "", "Key": "", "Icon": "", "PK_Store": "0" } ], "ZWaveStatus": 1, "Mode": 1, "LocalTime": "2016-07-17 14:25:44 D" }';
var myObject = JSON.parse(myJson);
console.log(myObject.Device_Num_6.states[0].id); // should return 207
Your json has invalid format. Because of that you couldn't to parse it as JSON.parse method. Try to check it here http://jsonviewer.stack.hu/
UPD: issue with this string "NewValue": "UserID=\"1\" UserName=\"Main\"". You should make it as "NewValue": "UserID=\\"1\\" UserName=\\"Main\\""
I have two arrays like this :
var friendemail = [ {
"data": {
"status": "OK",
"message": "User list fetched successfully",
"userList": [
{
"userId": 1,
"emailId": "abc.com",
"firstName": "Abc",
"lastName": "Xyz",
"nickName": "Nic",
"type": "USER",
"apiKey": "355901361"
},
{
"userId": 2,
"emailId": "babitadhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 3,
"emailId": "testuser#g.com",
"firstName": "Test_User",
"lastName": "Account",
"nickName": "Testi",
"type": "USER",
"apiKey": "1403626362113"
},
{
"userId": 4,
"emailId": "dhami#gmail.com",
"firstName": "dhami",
"lastName": "Dhami",
"nickName": "bobby",
"type": "DEVELOPER",
"apiKey": "222234567"
},
{
"userId": 5,
"emailId": "babita.dhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "1403709178117"
},
{
"userId": 6,
"emailId": "Chris#abc.com",
"firstName": "dhami",
"lastName": "dhami",
"nickName": "dhami",
"type": "DEVELOPER",
"apiKey": "333234567"
},
{
"userId": 7,
"emailId": "kevin.wei#qdevinc.com",
"firstName": "abc",
"lastName": "xyz",
"nickName": "none",
"type": "DEVELOPER",
"apiKey": "111234567"
},
{
"userId": 8,
"emailId": "dhamji#gmail.com",
"firstName": "Bab",
"lastName": "Dham",
"nickName": "bobby",
"type": "USER",
"apiKey": "1403790266057"
},
{
"userId": 9,
"emailId": "info#hemlockhills.ca",
"firstName": "Jenn",
"lastName": "Becker",
"nickName": "JennB",
"type": "USER",
"apiKey": "355901361"
},
{
"userId": 10,
"emailId": "babitadhami1#gmail.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 11,
"emailId": "b.dhami#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 12,
"emailId": "dhami.babita#g.com",
"firstName": "Babita",
"lastName": "Dhami",
"nickName": "bobby",
"type": "USER",
"apiKey": "333234567"
},
{
"userId": 13,
"emailId": "Francie#abc.com",
"firstName": "Francie",
"lastName": "Francie",
"nickName": "Francie",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 14,
"emailId": "Sam#abc.com",
"firstName": "Sam",
"lastName": "M",
"nickName": "S",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 15,
"emailId": "Sid#abc.com",
"firstName": "Sid",
"lastName": "B",
"nickName": "S",
"type": "USER",
"apiKey": "22234567"
},
{
"userId": 16,
"emailId": "tim#outlook.com",
"firstName": "tim",
"lastName": "tim",
"nickName": "tim",
"type": "USER",
"apiKey": "111234567"
},
{
"userId": 17,
"emailId": "racing#gmail.com",
"firstName": "racing",
"lastName": "racing",
"nickName": "Hollywood",
"type": "USER",
"apiKey": "222234567"
}
]
},
"status": 200,
"config": {
"method": "GET",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "OK"
}]
and another is
var deviceContactEmail = [
{
"id": "1",
"rawId": "1",
"displayName": "kandwal",
"name": {
"formatted": "kandwal",
"givenName": "kandwal"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "testuser#g.com",
"id": "6",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/1/photo",
"type": "url",
"id": "1",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "2",
"rawId": "2",
"displayName": "xyz",
"name": {
"formatted": "xyz ",
"givenName": "xyz"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "Chris#abc.com",
"id": "12",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/2/photo",
"type": "url",
"id": "7",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "3",
"rawId": "3",
"displayName": "cdf",
"name": {
"formatted": "cdf",
"givenName": "cdf"
},
"nickname": null,
"phoneNumbers": null,
"emails": null,
"addresses": [
{
"region": "Uk",
"id": "19",
"locality": "Dehra Dun",
"formatted": "dddd",
"type": "home",
"pref": false,
"country": "India"
}
],
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/3/photo",
"type": "url",
"id": "14",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "4",
"rawId": "4",
"displayName": "abcd",
"name": {
"formatted": "scd ",
"givenName": "scd"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "dhami#gmail.com",
"id": "26",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/4/photo",
"type": "url",
"id": "21",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "5",
"rawId": "5",
"displayName": "hiteshbhattcse#gmail.com",
"name": {
"formatted": "hiteshbhattcse#gmail.com ",
"givenName": "hiteshbhattcse#gmail.com"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "hiteshbhattcse#gmail.com",
"id": "33",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/5/photo",
"type": "url",
"id": "28",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "6",
"rawId": "6",
"displayName": "hitet#gmail.com",
"name": {
"formatted": "hitet#gmail.com ",
"givenName": "hitet#gmail.com"
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "hiteshbhatt#gmail.com",
"id": "40",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/6/photo",
"type": "url",
"id": "35",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "7",
"rawId": "7",
"displayName": null,
"name": {
"formatted": ""
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "mayank.th088#gmail.com",
"id": "46",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/7/photo",
"type": "url",
"id": "41",
"pref": false
}
],
"categories": null,
"urls": null
},
{
"id": "8",
"rawId": "8",
"displayName": null,
"name": {
"formatted": ""
},
"nickname": null,
"phoneNumbers": null,
"emails": [
{
"type": "other",
"value": "gcjoshi83#gmail.com",
"id": "53",
"pref": false
}
],
"addresses": null,
"ims": null,
"organizations": null,
"birthday": null,
"note": "",
"photos": [
{
"value": "content://com.android.contacts/contacts/8/photo",
"type": "url",
"id": "48",
"pref": false
}
],
"categories": null,
"urls": null
}]
I want to compare both of them for email id . and wanna get the common email id inside 1 array and rest in one array from deviceContactEmail.
I tried angular. each but not getting success.
var wUser = [];
var nonWUser = [];
angular.forEach(deviceContactEmail, function(phonevalue){
console.log(phonevalue);
angular.forEach(friendemail, function(value){
if (phonevalue.emails) {
if(phonevalue.emails[0].value === value.emailId){
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
}else{
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
nonWUser.push(phonevalue);
};
}
})
})
Hi Try this I solved to remove the duplicates value in the array check it...
var wUser = [];
var nonWUser = [];
angular.forEach(deviceContactEmail, function(phonevalue){
console.log(phonevalue);
angular.forEach(friendemail[0].data.userList, function (value) {
if (phonevalue.emails) {
if(phonevalue.emails[0].value === value.emailId){
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
}
else {
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
if ($scope.nonWUser.length == 0) {
nonWUser.push(phonevalue);
}
var filteredVal= $scope.nonWUser.filter(function (filterValue) {
return filterValue.emails[0].value == phonevalue.emails[0].value;
});
if (filteredVal.length == 0)
nonWUser.push(phonevalue);
}
}
});
});
check the edited file
It seem you are not pointing the inner loop at the right list. friendemail is a list but contains only one item. I assume the emailId you are testing for is buried inside the data which happens to be child of friendemail. Try the code below
angular.forEach(deviceContactEmail, function(phonevalue) {
console.log("................ ",phonevalue, " ", friendemail[0].data.userList.length);
angular.forEach(friendemail[0].data.userList, function(value) {
if (phonevalue.emails) {
if (phonevalue.emails[0].value === value.emailId) {
console.log(phonevalue.emails[0].value);
wUser.push(phonevalue);
} else {
console.log("------------------------------------------------------------------------");
console.log(phonevalue.emails[0].value);
nonWUser.push(phonevalue);
}
;
}
})
})