I have a problem. How can I get refcat in that Json object in javascript. Please find the below code snippet.
{
"request": {
"operation": "Viviendas",
"languague": "es",
"idMunicipio": "5",
"idVia": "196",
"idProvincia": "28",
"pc1": "9115501",
"pc2": "VK6891N",
"numero": "1"
},
"created_http": "Thu Oct 01 09:33:58 GMT+01:00 2015",
"created_server": 20151001092458,
"data": [
{
"portal": "",
"escaleras": [
{
"escalera": "1",
"plantas": [
{
"planta": "00",
"puertas": [
{
"puerta": "01",
"refCat": "9115501VK6891N0001GB",
"superficieVivienda": 60.0,
"superficieTotal": 60.0
}
]
},
{
"planta": "01",
"puertas": [
{
"puerta": "01",
"refCat": "9115501VK6891N0002HZ",
"superficieVivienda": 154.0,
"superficieTotal": 170.0
}
]
},
{
"planta": "02",
"puertas": [
{
"puerta": "01",
"refCat": "9115501VK6891N0003JX",
"superficieVivienda": 161.0,
"superficieTotal": 177.0
}
]
}
]
}
]
}
],
"page": "1",
"pagesTotal": "1",
"status_code": "200",
"status_text": "OK"
}
I tried to fix this with the below method.
alert(json.data[0].escaleras[0].plantas[0].puertas[i].refCat);
But it doesn't work. Can someone please help me with this?
Hi you would have to iterate through the json object to get the data.
Use the following code.
json.data.forEach(function (object) {
object.escaleras.forEach(function (innerObject) {
innerObject.plantas.forEach(function (innerMostObject) {
innerMostObject.puertas.forEach(function (refCatObject) {
console.log(refCatObject.refCat)
})
})
})
})
The problem is
alert(json.data[0].escaleras[0].plantas[0].puertas[i].refCat);
i is causing the problem...... ^
it should be 0.
alert(json.data[0].escaleras[0].plantas[0].puertas[0].refCat);
var json = {
"request": {
"operation": "Viviendas",
"languague": "es",
"idMunicipio": "5",
"idVia": "196",
"idProvincia": "28",
"pc1": "9115501",
"pc2": "VK6891N",
"numero": "1"
},
"created_http": "Thu Oct 01 09:33:58 GMT+01:00 2015",
"created_server": 20151001092458,
"data": [
{
"portal": "",
"escaleras": [
{
"escalera": "1",
"plantas": [
{
"planta": "00",
"puertas": [
{
"puerta": "01",
"refCat": "9115501VK6891N0001GB",
"superficieVivienda": 60.0,
"superficieTotal": 60.0
}
]
},
{
"planta": "01",
"puertas": [
{
"puerta": "01",
"refCat": "9115501VK6891N0002HZ",
"superficieVivienda": 154.0,
"superficieTotal": 170.0
}
]
},
{
"planta": "02",
"puertas": [
{
"puerta": "01",
"refCat": "9115501VK6891N0003JX",
"superficieVivienda": 161.0,
"superficieTotal": 177.0
}
]
}
]
}
]
}
],
"page": "1",
"pagesTotal": "1",
"status_code": "200",
"status_text": "OK"
};
alert(json.data[0].escaleras[0].plantas[0].puertas[0].refCat);
assuming you had a div with the id 'test' , this works. I'd guess it's your indexing logic generating the [i] on 'puertas' that's not correct, or perhaps your 'json' object isn't actually a JSON Object?
example jsfiddle https://jsfiddle.net/p6udz7ao/
copy of example below:
$(document).ready(function () {
var jsonString = '{ "request": { "operation": "Viviendas", "languague": "es" ,"idMunicipio":"5","idVia":"196","idProvincia":"28","pc1":"9115501","pc2":"VK6891N","numero":"1" }, "created_http": "Thu Oct 01 09:33:58 GMT+01:00 2015", "created_server": 20151001092458, "data": [ { "portal": "", "escaleras": [ { "escalera": "1", "plantas": [ { "planta": "00", "puertas": [ { "puerta": "01", "refCat": "9115501VK6891N0001GB", "superficieVivienda": 60.0, "superficieTotal": 60.0 } ] } , { "planta": "01", "puertas": [ { "puerta": "01", "refCat": "9115501VK6891N0002HZ", "superficieVivienda": 154.0, "superficieTotal": 170.0 } ] } , { "planta": "02", "puertas": [ { "puerta": "01", "refCat": "9115501VK6891N0003JX", "superficieVivienda": 161.0, "superficieTotal": 177.0 } ] } ] } ] } ], "page" : "1", "pagesTotal" : "1", "status_code" : "200", "status_text" : "OK" }';
var jsonObject = JSON.parse(jsonString);
var refcattext = jsonObject.data[0].escaleras[0].plantas[0].puertas[0].refCat;
$('#test').text(refcattext);
});
Related
I have JSON data which has structure as follows:
const SubSpecs= [
{
"_id": "1",
"nom": "installation",
"blocks": [
{
"idBlock": "1",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 12
}
]
},
{
"idBlock": "2",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 14
}
]
}
]
},
{
"_id": "2",
"nom": "tech",
"blocks": [
{
"idBlock": "1",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 12
}
]
},
{
"idBlock": "2",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 14
},
{
"idArtisan": "2",
"price": 50
}
]
}
]
}
],
}
this is the array of artisans that i want to filtered by its id's:
artisans= [
{
"_id": "1",
"username": "test1"
},
{
"_id": "2",
"username": "test2"
}
]
now i want to extract all prices that have the same id of artisan ( extract by id) and grouped by this id !!
i just start a simple function but i didn't find the way to finish it !!
can anyone help please !!
I am not able to understand how to filter such data ? Below code doesn't work I am not able to find any example of such filtering.
this is my function:
const total = data
.map((fb) =>
fb.blocks
.map((b) =>
b.ArtisanOffres.map((ao)=> ao.price)
.join(",")
.includes("1")
)
.join(",")
)
.join(",")
.split(",");
i'm new in javascript and i face this algorithm problem,
Ciao, what do you think about this solution? I filtered your data by idArtisan === "1", then sum all the prices. Result is 52. Here working example:
const SubSpecs= [
{
"_id": "1",
"nom": "installation",
"blocks": [
{
"idBlock": "1",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 12
}
]
},
{
"idBlock": "2",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 14
}
]
}
]
},
{
"_id": "2",
"nom": "tech",
"blocks": [
{
"idBlock": "1",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 12
}
]
},
{
"idBlock": "2",
"ArtisanOffres": [
{
"idArtisan": "1",
"price": 14
},
{
"idArtisan": "2",
"price": 50
}
]
}
]
}
];
let result = SubSpecs.map(sub => {
return sub.blocks.map(block => {
return block.ArtisanOffres.filter(artisan => artisan.idArtisan === "1");
});
});
let array = result.flat(2);
let final_sum = {};
final_sum.idArtisan = "1";
final_sum.total = array.reduce(function(_this, val) {
return _this + val.price
}, 0);
console.log(final_sum);
Explanation: Used 2 maps (because SubSpecs and blocks are arrays) then a filter for idArtisan. result.flat(2) is because maps result creates a 3-level array. Finally a reducer to sum prices.
This question already has answers here:
Find by key deep in a nested array
(21 answers)
Closed 4 years ago.
I have a Javascript object with lots of different sections. How can I search through all of the sections to find the position of a specific ID? The ID's that I am searching for are not in a specific location, and can be located in any of the tree branches.
For example, I am searching for this ID:
xobmnbjxg0g_1527269346261
And I am trying to output the position of that ID, which would be this:
app['structure'][0]['if-children'][0]['id']
My Javascript Object:
var app = {
"structure": [
{
"id": "0",
"type":"IF",
"parameters": [
{
"id": "xobmnbjxg0g_1527269346260",
"type": "field",
"value": "CV_TEST_SPOT1X"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children": [
{
"id": "xobmnbjxg0g_1527269346261",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children":[
],
"else-children":[
]
}
],
"else-children":[
{
"id": "xobmnbjxg0g_1527269346262",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
},
{
"id": "2",
"type": "operator",
"value": "="
},
{
"id": "3",
"type": "field",
"value": "North America"
}
],
"if-children":[
{
"id":"xobmnbjxg0g_152726934626X"
}
],
"else-children":[
{
"id":"xobmnbjxg0g_152726934626Y"
}
]
}
]
},
{
"id": "xobmnbjxg0g_1527269346263",
"type":"IF",
"parameters": [
[
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
]
],
"if-children": [
{
"id": "xobmnbjxg0g_1527269346264",
"type":"IF",
"parameters": [
[
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
]
],
"if-children":[
{
"id": "xobmnbjxg0g_1527269346265",
"type":"IF",
"parameters": [
{
"id": "1",
"type": "field",
"value": "CV_TEST_SPOT1"
}
],
"if-children":[
{
"id":"xobmnbjxg0g_1527269346266"
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346267"
}
]
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346268"
}
]
}
],
"else-children":[
{
"id":"xobmnbjxg0g_1527269346269"
}
]
}
]
};
Interesting puzzle/question.
pretty sure there are some edge cases im missing but this seems to pass some tests.
function is(obj, type){
return Object.prototype.toString.call(obj) === `[object ${type}]`;
}
function findPosition(obj, mykey, myval, res){
if(is(obj, "Object")){
if(mykey in obj && obj[mykey] === myval){
res.tree.push(mykey);
res.found = true;
} else {
for( let key in obj){
if(res.found) break;
res.tree.push(key);
findPosition(obj[key], mykey, myval, res);
}
if(!res.found) res.tree.pop();
}
} else if(is(obj, "Array")){
for(let i = 0; i < obj.length; i++){
if(res.found) break;
res.tree.push(i);
findPosition(obj[i], mykey, myval, res);
}
if(!res.found) res.tree.pop();
} else {
res.tree.pop();
}
return res;
}
Usage and output
findPosition([{one: { two: [{id: [{id:'my'}]}]}}], "id", "mys", {tree:[], found: false})
> tree: Array(0), found: false}
findPosition([{one: { two: [{id: [{id:'my'}]}]}}], "id", "my", {tree:[], found: false})
> {found: true, tree: [0, "one", "two", 0, "id", 0, "id"]}
For finding if current obj you are iterating over is an Array you can also use Array.isArray
I have elastic Search data in following format:
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "stellenbosch" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
},
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "Rustenburg" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
},
{
"is_cricketer": 0,
"name": "deVilliers",
"cities": [
{ "name": "Cape town" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
I need to query elastic search to get all the profiles with is_cricketer = 1 and an OR query over the field for cities.name and name field. ie
( profile.is_cricketer == 1 && (profile.name == 'Abraham' || profile.cities[i].name == 'Nelspruit' ))
To get the profiles with OR query on the fields cities.name and name field for matching query string is as follows and it works a expected:
"should": [
{
"nested": {
"path": "cities",
"query": {
"multi_match": {
"query": "Nelspruit",
"fields": [
"cities.name"
]
}
}
}
},
{
"multi_match": {
"query": "Abraham",
"fields": [
"name"
]
}
}
]
And the Must query to get all the profiles with field is_cricketer = 1 is follows:
{
"must": {
"match": {
"is_cricketer": "1"
}
}
}
Above both queries working fine and i am trying to combine both query as follows:
{
"query": {
"bool": {
"must": {
"match": {
"is_cricketer": "1"
}
},
"should": [
{
"nested": {
"path": "cities",
"query": {
"multi_match": {
"query": "Nelspruit",
"fields": [
"cities.name"
]
}
}
}
},
{
"multi_match": {
"query": "Abraham",
"fields": [
"name"
]
}
}
]
}
}
}
which is not returning expected results, its returning all the profiles with is_cricketer = 1 without filtering for name and cities.name.
I also tried to include the should query inside must query as follows:
{
"query": {
"bool": {
"must": [{
"match": {
"is_cricketer": "1"
}
}, {
"should": [
{
"nested": {
"path": "cities",
"query": {
"multi_match": {
"query": "Nelspruit",
"fields": [
"cities.name"
]
}
}
}
},
{
"multi_match": {
"query": "Abraham",
"fields": [
"name"
]
}
}
]
}]
}
}
}
But i got following error for the above query:
"Error: [parsing_exception] [should] query malformed, no start_object
after query name, with { line=1 & col=64 }
at respond (/GitRepo/project/node_modules/elasticsearch/src/lib/transport.js:307:15)
at checkRespForFailure (/GitRepo/project/node_modules/elasticsearch/src/lib/transport.js:266:7)
at HttpConnector. (/GitRepo/project/node_modules/elasticsearch/src/lib/connectors/http.js:159:7)
at IncomingMessage.bound (/GitRepo/project/node_modules/elasticsearch/node_modules/lodash/dist/lodash.js:729:21)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1056:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)"
How to combine both the queries to get desired result. Any help will be appreciated.
if you want a should query inside a must you can use it in the following way
{
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
... your query here
}
]
}
}
]
}
}
}
This worked for me on ES 6.0.
Setup
PUT test1
{
"mappings": {
"type1": {
"properties": {
"cities": {
"type": "nested"
}
}
}
}
}
POST test1/type1
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "stellenbosch" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
POST test1/type1
{
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{ "name": "Rustenburg" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
POST test1/type1
{
"is_cricketer": 0,
"name": "deVilliers",
"cities": [
{ "name": "Cape town" },
{ "name": "Nelspruit" },
{ "name": "East London" }
]
}
Query
GET test1/type1/_search
{
"query": {
"bool": {
"must": [
{
"term": {
"is_cricketer": {
"value": 1
}
}
}
],
"should": [
{
"term": {
"name.keyword": {
"value": "Abraham"
}
}
},
{
"nested": {
"path": "cities",
"query": {
"term": {
"cities.name.keyword": {
"value": "Nelspruit"
}
}
}
}
}
]
}
}
}
Results - 2 hits
"hits": {
"total": 2,
"max_score": 2.2685113,
"hits": [
{
"_index": "test1",
"_type": "type1",
"_id": "zgcesWIBVwCaLf8KSuDi",
"_score": 2.2685113,
"_source": {
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{
"name": "stellenbosch"
},
{
"name": "Nelspruit"
},
{
"name": "East London"
}
]
}
},
{
"_index": "test1",
"_type": "type1",
"_id": "eAQesWIBbxh35CpKckEH",
"_score": 2.2685113,
"_source": {
"is_cricketer": 1,
"name": "Abraham",
"cities": [
{
"name": "Rustenburg"
},
{
"name": "Nelspruit"
},
{
"name": "East London"
}
]
}
}
]
}
I have 2 orders in JSON.
[
{
"Type": "Example",
"booking_date": "2016-03-31T00:00:00.000Z",
"arriving_time": "2016-03-31T00:00:00.000Z",
"vendor": "b3d1d9c076a937929376e21b",
"buffer_time": "2016-03-31T00:00:00.000Z",
"order": [],
"items": []
}
]
[
{
"booking_date": "2016-03-31T00:00:00.000Z",
"order1": [
{
"max_item": "4",
"cost_per_package": "500",
"cost_per_item": "100",
"arrive_before_time": "2016-03-31T00:00:00.000Z"
}
]
}
]
I have to add order #1 details into order #2. How do I add it? it should add details as per booking date.
Order1
{
"order1": [
{
"Type": "Example",
"booking_date": "2016-03-31T00:00:00.000Z",
"arriving_time": "2016-03-31T00:00:00.000Z",
"vendor": "b3d1d9c076a937929376e21b",
"buffer_time": "2016-03-31T00:00:00.000Z",
"order": [],
"items": []
}
]
}
Order2
{
"order2": [
{
"booking_date": "2016-03-31T00:00:00.000Z",
"order1": [
{
"max_item": "4",
"cost_per_package": "500",
"cost_per_item": "100",
"arrive_before_time": "2016-03-31T00:00:00.000Z"
}
]
}
]
}
To copy contents of array order1 to order do something like this -
order1[0].order = angular.copy(order2[0].order1);
In javascript/jquery how do i achieve following
old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
Using jquery iterate over the above and change to following
new_dataset = [
{
"dob":"xyz",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
},{
"dob":"er",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
}]
If someone can give the code to transform the data it would help me to understand the iteration
You could do something like:
function transformDataset(oldDataset) {
var newDataset = [];
var newObj;
for (var i = 0; i < oldDataset.length; i++) {
newObj = transformObj(oldDataset[i]);
newDataset.push(newObj);
}
return newDataset;
}
function transformObj(obj) {
var children = obj.children;
obj.name = obj.name.first + ' ' + obj.name.last;
obj.start_date = obj.start_date.month + ' ' + obj.start_date.day + ' ' + obj.start_date.year;
obj.children = [];
for (var i = 0; i < children.length; i++) {
obj.children.push(children[i].child.id);
}
return obj;
}
var new_dataset = transformDataset(old_dataset);
Note that new_dataset will have an array of child id instead of an object with multiple child_id properties.
You also had a typo in old_dataset.start_date.month (was written moth)(or maybe that was intentional).
use map first to iterate the array data (old_dataset), replace element name & start_date with new value then return the array
const old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
let new_dataset = old_dataset.map((arr) => {
arr.name = `${arr.name.first} ${arr.name.last}`
arr.start_date = `${arr.start_date.moth} ${arr.start_date.day} ${arr.start_date.year}`
return arr
})
console.log(new_dataset)