Retrieve JSON Array element in ReactJS - json

I have the following json file in ReactJS:
{
"locations": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
How can I get the value of a an element where the id=xxxx? Also how can I get the loc when id=xxxx?

you can use underscorejs
let array_of_ids = _.pluck(json_object.locations,"id")
//now find the index of your particular id
let index = _.indexOf(array_of_ids,yourId)
//now your required object is
let your_object = json_object.locations[index]
Thats it
cheers

You can use the filter function.
var obj = {
"locations": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}
var val = '8817';
var res = obj.locations.filter(function(item) {
return item.id == val;
});
console.log(res[0].loc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>

Related

Get Values form Json, using jpath

{
"data": [
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "abx",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800001"
}
},
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "xyz",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800002"
}
},
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "ijk",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800003"
}
}
]
}
Out put json should be like this
[
{
"name": "abx",
"Pin": "800001"
},
{
"name": "xyz",
"Pin": "800002"
},
{
"name": "ijk",
"Pin": "800003"
}
]
From the input json, I want to extract all values using
jpath
Name Path = "data.name"
Pin Path = "data.address.pin"
I need all values, I will create an output json.
If both json and jpath are dynamic then try using the below code, here i have used the same input json and output json in my code block.
$(document).ready(function () {
var outputArr = [];
//Assume that these jpaths are dynamic.
var name = "data.name", pin = "data.address.Pin";
//Assigned input json object to sampleData variable.
$.each(sampleData.data, function (item, value) {
//Replacing 'data.' with empty('') as we are looping through data array.
var nameValue = extractValue(value, name.replace('data.', ''));
var pinValue = extractValue(value, pin.replace('data.', ''));
outputArr.push({ 'name': nameValue, 'Pin': pinValue });
});
//logging into console for testing purpose.
console.log(outputArr);
--to do with outputArr --
//Recursive function that returns the required value from the json
function extractValue(value, jPathKey) {
if (jPathKey.split(".").length > 1) {
//Here use of replace function is must as we need to get the object with the mentioned jPathKey to loop further.
return extractValue(value[jPathKey.replace('.', '$').split('$')[0]], jPathKey.replace('.', '$').split('$')[1])
}
else {
return value[jPathKey];
}
}
});
Note: Here only thing that need to take care is the case of jpath should match with case of input json

How access the access the whole object by its id

Here we are having two JSON called 1.contacts and 2.workers contacts json is having id called serviceId is nothing but id of workers. when i try to display contacts i want to display workers relevant to that contacts. Here is the stackblits DEMO
Here i have updated stackblitz using sample your data as Array.
https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-ujzzx1
Code:-
let finalResult:any[]=[];
for(let contact of this.contacts){
if(contact.serviceId){
finalResult.push(this.workers.filter(o=>o.id == contact.serviceId));
}
}
console.log("finalResult",finalResult);
You can gather the IDs from the contacts IDs in a map by using map then reduce. After that you iterate over your workers and check in the previously generated map if their serviceId is one of the map's keys.
It looks like this
const contacts = [{
"name": "Jhon Doe",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Peter Parker",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Mark Wood",
"gender": "Male",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
},
{
"name": "Mary Jane",
"gender": "Female",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
}
];
const workers = [
{
"id": "e39f9302-77b3-4c52-a858-adb67651ce86",
"name": "Alfy Odhams"
},
{
"id": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
"name": "Allsun Suttle"
},
{
"id": "ed780d15-428b-4bcd-8a91-bacae8b0b72e",
"name": "Alvinia Ettritch"
},
{
"id": "40665c50-ff74-4e81-b968-e127bdf1fe28",
"name": "Ambrosi Lindenstrauss"
}
];
const contactsIDs = contacts.map(c => c.serviceId).reduce((acc, curr) => {
acc[curr] = true;
return acc;
}, {});
const filteredWorkers = workers.filter(w => w.id in contactsIDs);
console.log(filteredWorkers);

How to loop through JSON object?

How can we loop through given JSON object to traverse all its properties:
<script type="text/javascript">
var students = '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';
var myObj = JSON.parse(students);
alert(myObj.name);
alert(myObj.age);
alert(myObj.subjects[0]['name']);
alert(myObj.subjects[0]['marks']);
alert(myObj.subjects[1]['name']);
alert(myObj.subjects[1]['marks']);
alert(myObj.subjects[2]['name']);
alert(myObj.subjects[2]['marks']);
</script>
You can see I am accessing nested "subject" properties by using its index and property name. But the code becomes lengthy to traverse each items. To avoid it, I am wondering how to loop (e.g. for in loop) through by writing single line of code to access all its properties?
You could do this:
var myObj = JSON.parse(students);
for(var index = 0; index < myObj.subjects.length; index++) {
alert(myObj.subjects[index]['name']);
alert(myObj.subjects[index]['marks']);
}
Just use Each function to iterate the each subjects
var students = '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';
var myObj = JSON.parse(students);
$.each(myObj['subjects'], function(index, value) {
console.log(value['name']+" "+ value['marks']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try using stringify
var myObj = JSON.stringify(students);
for(var index=0;index < myObj.subjects.length;index++) {
alert ( myObj.subjects[index] );
}

How to control keys to show in Json Object

I am using following NodeJs code to get the JsonObject:
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index];
}
res.send(resp);
});
Getting output :
{
"emp1": {
"cas": {
"0": 637861888,
"1": 967242753
},
"flags": 0,
"value": {
"eid": "10",
"ename": "ameen",
"gender": "male",
"designation": "manager",
"country": "Singapur",
"reportee": "Suresh",
"salary": 50000,
"picture": "ameen.jpg"
}
},
"emp2": {
"cas": {
"0": 721747968,
"1": 430939000
},
"flags": 0,
"value": {
"eid": "2",
"ename": "shanmugapriya",
"gender": "female",
"designation": "programmer",
"country": "England",
"reportee": "shruti",
"salary": 14250,
"picture": "priya.jpg"
}
}
}
What I want to do is, I want to display only value key. Can anybody help me how to do this.
Thanks in advance.
Do you mean you want to display only value and key? If so the code below will put only value into the result
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index].value;
}
res.send(resp);
});
The result response will be
{
"emp1":{
"eid":"10",
"ename":"ameen",
"gender":"male",
"designation":"manager",
"country":"Singapur",
"reportee":"Suresh",
"salary":50000,
"picture":"ameen.jpg"
},
"emp2":{
"eid":"2",
"ename":"shanmugapriya",
"gender":"female",
"designation":"programmer",
"country":"England",
"reportee":"shruti",
"salary":14250,
"picture":"priya.jpg"
}
}
UPDATE: Your question was really ambiguous. I think you would need to use Couchbase Views here. Docs http://docs.couchbase.com/couchbase-sdk-node-1.2/#querying-a-view. Assuming that you will build the view _design/employees/_view/all with the following map function:
function(doc, meta) {
emit(meta.id, doc);
}
Your node.js code will look like this
var view = bucket.view('employees', 'all');
view.query(function(err, results) {
res.send(results);
});

Search JSON for multiple values, not using a library

I'd like to be able to search the following JSON object for objects containing the key 'location' then get in return an array or json object with the 'name' of the person plus the value of location for that person.
Sample return:
var matchesFound = [{Tom Brady, New York}, {Donald Steven,Los Angeles}];
var fbData0 = {
"data": [
{
"id": "X999_Y999",
"location": "New York",
"from": {
"name": "Tom Brady", "id": "X12"
},
"message": "Looking forward to 2010!",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X999/posts/Y999"
},
{
"name": "Like",
"link": "http://www.facebook.com/X999/posts/Y999"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
},
{
"id": "X998_Y998",
"location": "Los Angeles",
"from": {
"name": "Donald Steven", "id": "X18"
},
"message": "Where's my contract?",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X998/posts/Y998"
},
{
"name": "Like",
"link": "http://www.facebook.com/X998/posts/Y998"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
}
]
};
#vsiege - you can use this javascript lib (http://www.defiantjs.com/) to search your JSON structure.
var fbData0 = {
...
},
res = JSON.search( fbData0, '//*[./location and ./from/name]' ),
str = '';
for (var i=0; i<res.length; i++) {
str += res[i].location +': '+ res[i].from.name +'<br/>';
}
document.getElementById('output').innerHTML = str;
Here is a working fiddle;
http://jsfiddle.net/hbi99/XhRLP/
DefiantJS extends the global object JSON with the method "search" and makes it possible to query JSON with XPath expressions (XPath is standardised query language). The method returns an array with the matches (empty array if none were found).
You can test XPath expressions by pasting your JSON here:
http://www.defiantjs.com/#xpath_evaluator