How to control keys to show in Json Object - json

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);
});

Related

Postman accessing child objects in Json in a Test

I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.

Sequelize Insert Cascade

im trying insert in multiple tables.
let me explain User create a new client, client insert id into bill - (idClient) table
this is the payload
{
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"services": [1, 2, 3],
"bill":{
"description": "New project"
}
}
the insert
_service.create = async (client) => {
const { description } = client.bill;
try {
const data = await Client.create(
{ client, bill: { description: description } },
{ include: { model: Bill } }
);
return data.id;
} catch (err) {
handleError = err.hasOwnProperty("errors")
? err.errors.map((error) => error.message)
: err;
throw new Error(handleError);
}
};
but im getting this error
{
"name": "Error",
"message": "ReferenceError: description is not defined"
}
and yes, bill table has that column.
the relation
Client.hasOne(models.Bill, { foreignKey: "idClient" });
so, im stuck, i read the documentation and i trying to do the same way as they do but i dont know what i doing wrong
https://sequelize.org/master/manual/creating-with-associations.html
I already did, i dont know if the best way
i modified the payload
{
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"description": "new Proyect",
}
the insert query, change bill to Bill as my table name and then add description value
const { description } = client;
const data = await Client.create(
{ ...client, Bill: { description } },
{ include: { model: Bill } }
);
and the result
{
"id": 6,
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z",
"Bill": {
"id": 4,
"idClient": 6,
"totalAmount": null,
"description": "new Proyect",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z"
}
}

Mapping data that contains dots in React

I am trying to map the data in React that is coming from the API but I am having problems mapping the object that contains dots for example this: name.en_US.
What is the proper way to map this object and keeping the data structure that I have?
I am getting the date in this format from the API:
{
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
},
And then I am trying to map it using the following code.
const {
user,
employeeId,
businessCustomer,
endCustomer,
device,
task
} = task;
const{
endCustomerName,
address,
place
} = endCustomer;
const {
shipmentIds,
names
} = device;
const{
en_US,
fi_FI
} = names;
const {
time,
duration,
summa
} = task;
const data = {
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
};
const { device } = data;
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
const nameUS = device['name.en_US'];
console.log(name_en_US, nameUS);
Use [ ] notation like, device['name.en_US'] .
You can destructure your propery as #Vishnu mentioned, or you could also destructure it by providing a valid key name
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
And then you could access your variable with name_en_US.

couchdb ; how get documents directly in first level of json, and not grouped inside value - viewWithList

I have a design document: 'accounts',and the view: 'accounts-view'
the view's content is:
function (doc) {
emit( doc._id, doc);
}
And my code in express is:
db.view('accounts', 'accounts-view', function(err, body) {
if (err) throw error;
res.json(body.rows);
});
Result is:
[
{
"id": "8767d3474a0e80dd0ab7d0b0580065af",
"key": "8767d3474a0e80dd0ab7d0b0580065af",
"value": {
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
}
},
{
"id": "8767d3474a0e80dd0ab7d0b058006e3c",
"key": "8767d3474a0e80dd0ab7d0b058006e3c",
"value": {
"_id": "8767d3474a0e80dd0ab7d0b058006e3c",
"_rev": "1-bcab94bb253c83b4951a787c253896f5",
"type": "accounts",
"lastname": "Kolner",
"firstname": "John"
}
}
]
How i can get just something like this: ( just printing all is inside value for every row)
[
{
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
},
{
"_id": "8767d3474a0e80dd0ab7d0b058006e3c",
"_rev": "1-bcab94bb253c83b4951a787c253896f5",
"type": "accounts",
"lastname": "Kolner",
"firstname": "John"
}
]
UPDATE:
I've follow Domonique's suggestions ; and now I have a new view, that emit just the id (so i can save space on disk and retrive de doc with the parameter "include_docs=true" on the view):
function(doc) {
if (doc.type && doc.type=='accounts') {
emit( doc._id);
}
}
and a new list:
function(head, req) {
provides('json', function() {
var results = [];
while (row = getRow()) {
//results.push(row.value);
results.push(row.doc);
}
send(JSON.stringify(results));
});
}
Finally i get the records with:
http://127.0.0.1:5984/crm/_design/crmapp/_list/accounts-list/accounts-view?include_docs=true
and the result is:
[
{
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
},
{
"_id": "8767d3474a0e80dd0ab7d0b058006e3c",
"_rev": "1-bcab94bb253c83b4951a787c253896f5",
"type": "accounts",
"lastname": "Kolner",
"firstname": "John"
},
{
"_id": "8767d3474a0e80dd0ab7d0b058008e9a",
"_rev": "1-86078f00be82b97499a0f52488cefbbf",
"lastname": "Tower",
"firstname": "George",
"type": "accounts"
}
]
my app node express updated:
db.viewWithList('crmapp', 'accounts-view','accounts-list', {"include_docs":"true"} , function(err, body) {
if (err) throw err;
res.json(body);
});
with this list , I don't need more reduce it on express project, it's ok ?
How to udate my list or view to get by id ? it'not working just adding id on the url ; like this:
http://127.0.0.1:5984/crm/_design/crmapp/_list/accounts-list/accounts-view?include_docs=true&_id=8767d3474a0e80dd0ab7d0b058006e3c
I get all the records and not the only one by id
To answer your question here, you should simply map the array and only include the value portion:
db.view('accounts', 'accounts-view', function(err, body) {
if (err) throw error;
res.json(body.rows.map(function (row) {
return row.value;
}));
});
Since it's apparent you are new to CouchDB, I'll also give you some advice regarding views. First, the view you've created is actually just a duplicate of the system view _all_docs, so you should just use that instead rather than creating your own view. (especially since you've effectively created a duplicate on disk)
However, it is probably pretty likely that as you get further along in your application, you'll be using real views that partition documents differently depending on the query. As such, you should not emit your entire document (ie: doc) in your view function. By doing this, you are effectively duplicating that document on disk, since it will be represented in your database, as well as the view index.
The recommended starting point is to simply leave out the 2nd argument of your emit.
function (doc) {
emit(doc._id);
}
When you query the view, you can simply add include_docs=true to the URL and your view will look something like this:
[
{
"id": "8767d3474a0e80dd0ab7d0b0580065af",
"key": "8767d3474a0e80dd0ab7d0b0580065af",
"value": null,
"doc": {
"_id": "8767d3474a0e80dd0ab7d0b0580065af",
"_rev": "1-37eb3e76e4715e9a4fc8930470cc4ca3",
"type": "accounts",
"lastname": "Kitchen",
"firstname": "Peter"
}
}
// ...
]
Then, you can retrieve the doc instead of value to achieve the same result much more efficiently.

How to display data from a json file in angularjs?

I have a json something like this
{
"count": 67,
"0": {
"id": "2443",
"name": "Art Gallery",
"category": {
"id": "2246",
"name": "Gifts & Memories"
},
"deckLocation": [
{
"id": "2443",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
},
"1": {
"id": "7198",
"name": "Captain's Circle Desk",
"category": {
"id": "352",
"name": "Other Services"
},
"deckLocation": [
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
},
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
}
}
I want to display all names which is inside the "0", "1" array. I can able to list a specific name but not all. The fist name will display which I written in the following code. But I need to display all 0, 1, 2, 3 etc names dynamically.
data[0].name
Please help me.
Thank you.
use ng-repeat function to do so.
<div ng-repeat = "names in data">
<P>{{names.name}}</P>
</div>
Let us say you have a service like this:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.getUrl = function (urlToGet) {
var svc=this;
var deferred = $q.defer();
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
deferred.resolve(data); });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data });});
return (deferred.promise);
}
return service;
}]);
And you want to load a file named '/js/udata.json'. Here is how in you controller you can load this file:-
todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
$timeout(function(){
dbService.getUrl('/js/udata.json').then(function(resp){
$scope.todo=resp;
});},1);
};
Hope this helps!
You have data[0].name right?
then why don't you loop through that to get all the name elements in those arrays.
like...
for(i=1;i<data.length;i++)
{
console.log(data[i].name);
}