Access Json array - javascript

I have the following JSON I get sent back from my database and I am trying to access the 'name' and 'contact's keys:
[
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
},
{
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}
]
My java script callback function looks something like this and inside I am trying to print the values from the entities variable:
dataset.get(keys, function(err, entities) {});
I tried: entities.key.name[0] to get the first name key value, but it does not work. I am also stuck how to then get the contacts variable.

You can try something like this:
var json = [{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
}, {
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}]
function getJSONValues(){
var names = [], contacts = [];
for (var obj in json){
console.log(json[obj]);
names.push(json[obj].key.name);
contacts.push(json[obj].data.contacts.splice(0));
}
console.log(names, contacts)
}
getJSONValues();

Use console to see what is what:
var entities = [
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
},
{
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}
];
console.log(entities);
console.log(entities[1].key.name);
console.log(entities[1].data.contacts[0]);

if the variable to which this JSON object is assigned to is entities
then
entities[ 0 ][ "key" ].name; //will give you name
entities[ 0 ][ "data" ].contacts; //will give you contacts
now you can iterate the entities as
entities[ counter ][ "key" ].name; //will give you name
entities[ counter ][ "data" ].contacts; //will give you contacts

You have an array. So you have to use an index to read an item from it.
entities[0]
returns the first object.
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
}
The you can use either the dot notation or brackets notation to read the values of your object. For instance, if you want to read the key, just try this:
entities[0].key
Now key has a reference to the following object:
{
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
}
So, if you want to get the name, just do one more step:
entities[0].key.name
The same holds for the contacts:
entities[0].data.contacts

Use entities[ 0 ][ "key" ].name; as entities is an array

Related

How to get actual keys from MongoDB result array?

INPUT:
let array =[
{name:"xyz", email:"xyz#gmail.com", date:"22/10/2020" },
{name:"abc", email:"abc#gmail.com", date:"29/12/2020" },
{name:"efg", email:"efg#gmail.com", date:"20/01/2021" },
{name:"pqr", email:"pqr#gmail.com", date:"12/08/2020", age:"20" },
{name:"stu", email:"stu#gmail.com", date:"19/09/2020", age:"21" },
]
After performing certain operations I got the above array of objects as output from mongodb collection. From that array I want to get all keys and compare each and every object in an array and if any property present in any object not there in another object then I want to assign the property with empty string value.
To perform that operation I have written the code as shown below-
const keys = array.reduce(
(acc, curr) => (Object.keys(curr).forEach((key) => acc.add(key)), acc),
new Set()
);
const output = array.map((item) =>
[...keys].reduce((acc, key) => ((acc[key] = item[key] ?? ""), acc), {})
);
By performing above operations along with my original keys I am getting unnecessary keys like "$__", "$isNew", "_doc"
MY OUTPUT:
[
{
"$__": {
"activePaths": {
"paths": {
"_id": "init"
},
"states": {
"ignore": {},
"default": {},
"init": {
"_id": true
},
"modify": {},
"require": {}
},
"stateNames": [
"require",
"modify",
"init",
"default",
"ignore"
]
},
"strictMode": false,
"skipId": true,
"selected": {},
"fields": {},
"exclude": null
},
"$isNew": false,
"_doc": {
"_id": "62e6791b049e103f612f0882",
"name": "pqr",
"email": "pqr#gmail.com",
"date": "12/8/2020",
"age": "20",
},
"name": "pqr",
"email": "pqr#gmail.com",
"date": "12/8/2020",
"age": "20",
},
.
.
.
.
EXPECTED OUTPUT:
[
{
"name": "xyz",
"email": "xyz#gmail.com",
"date": "22/10/2020",
"age": ""
},
{
"name": "abc",
"email": "abc#gmail.com",
"date": "29/12/2020",
"age": ""
},
{
"name": "efg",
"email": "efg#gmail.com",
"date": "20/01/2021",
"age": ""
},
{
"name": "pqr",
"email": "pqr#gmail.com",
"date": "12/08/2020",
"age": "20"
},
{
"name": "stu",
"email": "stu#gmail.com",
"date": "19/09/2020",
"age": "21"
}
]
If I am using same code for normal array instead of resultant array from mongoodb I am getting correct output.
Please help me in resolving the above issue.
Query
if you have few fields and you know their names you can do it on server like bellow, in simple way
check if field (if missing it will be false) if its there keep old value, else add it with ""
the bellow doesn't work with boolean fields, if you have those you should check if type="missing" but in your case you dont have boolean fields so it will be ok
Playmongo
aggregate(
[{"$set":
{"name": {"$cond": ["$name", "$name", ""]},
"email": {"$cond": ["$email", "$email", ""]},
"date": {"$cond": ["$date", "$date", ""]},
"age": {"$cond": ["$age", "$age", ""]}}}])

MongoDB aggregation use $elemMatch for nested array

I try to learn aggregation concept in MongoDB. I create an object like this for training.
"_id": "601c4bb56e018211b02abbf8",
"isDeleted": false,
"name": "TeacherName1",
"class": "7",
"students": [
{ "_id": "601c4bb56e018211b02abbf9", isDeleted:true, "name": "student-1", "studentGroup": "A", "avgResult": 36},
{ "_id": "601c4bb56e018211b02abbfa", isDeleted:false, "name": "student-2", "studentGroup": "A", "avgResult": 55},
{ "_id": "601c4bb56e018211b02abbfb", isDeleted:false, "name": "student-3", "studentGroup": "B", "avgResult": 44.66},
{ "_id": "601c4bb56e018211b02abbfc", isDeleted:false, "name": "student-4", "studentGroup": "C", "avgResult": 83.66},
{ "_id": "601c4bb56e018211b02abbfd", isDeleted:true, "name": "student-5", "studentGroup": "B", "avgResult": 37},
{ "_id": "601c4bb56e018211b02abbfe", isDeleted:true, "name": "student-6", "studentGroup": "C", "avgResult": 39.66},
]
I want to get teacher information and deleted students (isDeleted=true). So I try to get this result.
"_id": "601c4bb56e018211b02abbf8",
"isDeleted": false,
"name": "TeacherName1",
"class": "7",
"students": [
{ "_id": "601c4bb56e018211b02abbf9", isDeleted:true, ...},
{ "_id": "601c4bb56e018211b02abbfd", isDeleted:true, ...},
{ "_id": "601c4bb56e018211b02abbfe", isDeleted:true, ...},
]
I get result with use $unwind and $filter. But can I get this result with only $elemMatch?
If I use this query
this.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId("601c4bb56e018211b02abbf8"),
isDeleted: false,
"students.isDeleted":true
},
},
]);
It returns all object.
If I try this
this.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId("601c4bb56e018211b02abbf8"),
isDeleted: false,
students:{
$elemMatch:{
isDeleted:true
}
}
},
},
]);
It returns all object.
$match will just give you the whole doc should you match
however you may use $project with $filter using another stage
given
db.dummy.insert({studs:[{isDeleted:true, name:'a'},{isDeleted: true, name:'b'},{name:'c'}]})
db.dummy.insert({studs:[{name:'c'}]})
> match = {$match:{studs:{$elemMatch: {isDeleted:true}}}}
> project = {$project: { deletedStuds: {$filter:{input: '$studs', as:'stud', cond:{ $eq: ['$$stud.isDeleted', true]} } } }}
{
"$project" : {
"deletedStuds" : {
"$filter" : {
"input" : "$studs",
"as" : "stud",
"cond" : {
"$eq" : [
"$$stud.isDeleted",
true
]
}
}
}
}
}
> db.dummy.aggregate(match, project)
{ "_id" : ObjectId("6020351eb965951ac8a1eb62"), "deletedStuds" : [ { "isDeleted" : true, "name" : "a" }, { "isDeleted" : true, "name" : "b" } ] }

JS How to remove an object from array in a forEach loop?

I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

How to convert array of objects to object with index?

I have a array like this->
var jsonResponse = [
{
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
{
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
And I want to convert it to ->
{
"abc" : {
"name": "abc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
},
"ccc": {
"name": "ccc",
"value": [
{ "label" : "Daily", "value":"Daily"}
]
}
]
Probably I dont want foreach.
We can do partial with Object.assign( arrayDetails, ...jsonResponse);
But how to do object index?
let indexedResult = {};
jsonResponse.map(obj => indexedResult[obj.name] = obj)
console.log(JSON.stringify(indexedResult));

split out object property and values from an array [duplicate]

This question already has answers here:
Remove a JSON attribute [duplicate]
(2 answers)
Closed 7 years ago.
From this json arrays
{
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
}
How to split out some field and turn it intosomething like this
{
"result": [
{
"id": "1",
"type": "B",
},
{
"id": "2",
"type": "A",
}
]
}
I do not want to use splice in my case, above is just sample code.
Try this:
var input = {
"result": [
{
"id": "1",
"name": "John",
"type": "B",
"score":"passed"
},
{
"id": "2",
"name": "Alice",
"type": "A",
"score":"failed"
}
]
};
var output = {
result: input.result.map(function(item) {
return {
id: item.id,
type: item.type
};
})
}
Try like this
var json = {
"result": [{
"id": "1",
"name": "John",
"type": "B",
"score": "passed"
}, {
"id": "2",
"name": "Alice",
"type": "A",
"score": "failed"
}
]
};
json.result.forEach(function(item) {
delete item.name;
delete item.score;
});
console.log(json);
iterate over arry and remove age property
var json = [
{"name":"john",
"age":"30",
"gender":"male"},
{"name":"Alice",
"age":"20",
"gender":"female"}
];
json.forEach(function(x){
delete x['age'];
})

Categories

Resources