Replace every array in object by first element of that array - json

I have a json like this:
"Client" : {
"ClientId" : "eertertwetw",
"Username" : "c.client",
"Names" : [
{
"Family" : "ClientFamilyName",
"Given" : [
"ClientGivenName"
]
}
]
}
This json is not fixed, so sometimes there are some properties and sometimes not.
I need to replace every array inside this Json with the first element of that array. So, for example, in this case it would be like
"Client" : {
"ClientId" : "eertertwetw",
"Username" : "c.client",
"Names" :
{
"Family" : "ClientFamilyName",
"Given" :
"ClientGivenName"
}
]
}
Can anyone help me to find a way to do this with Typescript?

Ok, I tried something (haven't tested it against all possible cases) but it seems like it's working.
Stackblitz - check the console for result.

let data = { Client: {...} }; // your data
data = data.map(client => {
if (!Object.hasOwnProperty(client.Names, 'Prefix')) {
client.Names.Prefix = null;
}
return client;
});

You need get the firt element in array in object.
like : Client.Names[0].Given[0].ClientGivenName

Related

How to update the whole array of objects using Put http request with a json raw body?

I have a json Array something like below and I want to make an update to the whole list without passing by a specefic ID.
List before update
[ { id:"1", name : "name_1" }, { id:"2", name : "name_2" } ]
Wanted list after update
[ { id:"1", name : "name_3" }, { id:"2", name : "name_4" } ]
I tried using PUT request and passing the target list in a json raw body, but it always return "404 not found"
I tried it with Postman but it returns the same error. Is it possible to do like so ?

Workaround to add JSON with errors to mongodb atlas collection

In my database class we were given an assignment to work with two JSON files (add them to a mongodb atlas collection and query certain results)
Both JSON files had "errors" the first being :
{ "_id" : { "$oid" : "50b59cd75bed76f46522c34e" }, "student_id" : 0, "class_id" : 2, "scores" : [ { "type" : "exam", "score" : 57.92947112575566 }, { "type" : "quiz", "score" : 21.24542588206755 }, { "type" : "homework", "score" : 68.19567810587429 }, { "type" : "homework", "score" : 67.95019716560351 }, { "type" : "homework", "score" : 18.81037253352722 } ] }
and the second being :
{"_id":0,"name":"aimee Zank","scores":[{"score":1.463179736705023,"type":"exam"},{"score":11.78273309957772,"type":"quiz"},{"score":35.8740349954354,"type":"homework"}]},
{"_id":1,"name":"Aurelia Menendez","scores":[{"score":60.06045071030959,"type":"exam"},{"score":52.79790691903873,"type":"quiz"},{"score":71.76133439165544,"type":"homework"}]},
I fixed error 1 by removing the $oid and replacing it with just oid: as there was an error trying to add objects with $oid as a value to my collection. I also needed to add everything to an array.
I fixed the second by putting the entire object inside an array [].
When I asked my professor why these errors were in the JSON files and if it was on purpose, he said that they were there on for a reason and that we needed to find a "work around".
I am curious what work around there is to load JSON data that is incorrect into a collection? I am at a complete loss as to what he expected. Is there some way I can just load individual objects line by line from the JSON file to the collection?
This is how I loaded the JSON data after fixing the files directly:
const fs = require('fs');
var data = JSON.parse(fs.readFileSync("./students.json"));
JSON.stringify(data);
const database = "college";
const collection = "students";
use(database);
db.students.drop();
db.createCollection(collection);
db.students.insertMany(data);
--- All the importing of data should be done in VS Code and not using --mongodb import
And a side note that this assignment has since passed so I am not asking for help in completing my homework, simply trying to see if there was something I could of done that would not of required me to edit the JSON file itself. My professor has not responded to me regarding this question.

Converting Elastic Search field to Array

In elastic search if you have document that has a pre-existing array
"movies": [
"Back to the Future"
]
And then you update it to add more movies like such
{
"script" : "ctx._source.movies += tag",
"params" : {
"tag" : "Pulp Fiction"
}
}
Then the value is added to the field. That works great... but what if the field isn't an arry to start with and instead looks like this
"movies": "Back to the Future"
If you run the same script you will get the following result
"movies":"Back to the FuturePulpFiction"
So my question is how do I take this existing field and "convert" it to an array to tell elastic search that I want to think of it as an array?
You can use this script instead. It checks whether movies is an array and if not it creates one
{
"script" : "if (ctx._source.movies.getClass().isArray()) { ctx._source.movies += tag } else { ctx._source.movies = [ctx._source.movies, tag] }",
"params" : {
"tag" : "Pulp Fiction"
}
}
Another shorter way of doing it is to always assign an array and then "flatten" it using Groovy's Collection.flatten() method
{
"script" : "ctx._source.movies = [ctx._source.movies, tag].flatten()",
"params" : {
"tag" : "Pulp Fiction"
}
}
Adding to the answer from Val, if ctx._source.movies does not exist it will add a null to your resulting list. Following is the script I use to do something similar but not include the null.
{
"script": "if (ctx._source.movie.getClass().isArray()) {ctx._source.event += tag} else if (ctx._source.movie) {ctx._source.movie = [ctx._source.movie, tag]} else {ctx._source.movie=[tag]}",
"params" : {
"tag" : "Pulp Fiction"
}
}

using JSON file to define array values in Node.js

In node.js my program app.js, i am defining array like this
var myList = [["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]];
console.log (myList)
It is giving output but i want an external JSON file to supply the parameter of myList array instead of me defining it hardcore
i have prepared a JSON file named ppm.json and change my code to
var myList = JSON.parse(fs.readFileSync('ppm.json', 'utf8'));
console.log (myList[1])
my ppm.json is this
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}
it giving me output as undefined in console. what is the problem. pls help.
Without more requirements it's hard to give a definitive answer, but one thing you can do:
app.js
var myList = require('./my_list.json');
console.log(myList);
my_list.json
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
You can use require() to load both JSON and JavaScript files.
For example,
myFile.json:
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
app.js:
var myList = require( './myFile.json' );
console.log (myList)
You're accessing your item wrong. You don't have an array you have an object.
Access your heros age like this:
myList['age']
You might also consider changing your file to look like this:
{
"SAHRUKH" : {
"age" : "47.49",
"lastpict" : "HIT"
}
}
In which case you'd get your hero's age like:
myList.SAHRUKH.age;
//Or Equivalently
myList['SAHRUKH']['age']; //The dot notation above is preferred though!
Or this
{ "heros" : [
{
"name" : "SAHRUKH",
"age" : "47.49",
"lastpict" : "HIT"
}
]}
In which case you'd get at age like:
myList.heros[0].age;
If you adjust your ppm.json file to look like:
[{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}]
It should drop in and work directly. If you wanted to include multiple heroes, it would look like:
[
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
},
{
"hero": "SALMAN",
"age": "47.3",
"lastpict": "FLOP"
}
]
Your resulting myList should be an array in the example you provided, with entry 0 being the first hero object (SAHRUKH) and 1 being the second, and so on.

Mongo find() query with embedded JSON object not returning data

I'm using Mongoose to query Mongo in Node.js, using this command:
var qw = {
'permissions': {'ownerID':req.user._id}
};
landmarkSchema.find(qw, function(err, lm) {
console.log(lm);
});
Where req.user._id = "53baf81408802a00002166b8"
But nothing is returning. I tried the same query in the Mongo terminal.
My data objects are constructed as:
{
"_id" : ObjectId("53bb736dbe211d0000f01837"),
"name" : "and",
"permissions" : {
"ownerID" : "53baf81408802a00002166b8",
"admins" : [ ],
"viewers" : [ ]
},
"__v" : 0
}
I also tried storing the ownerID as a Mongo ObjectID, i.e. ObjectId("53baf81408802a00002166b8") but that didn't seem to work either.
Use dot notation:
var qw = {
'permissions.ownerID': req.user._id
};
As written, your query above is searching for a document where the permissions property exactly matches your object, meaning it only has an ownerID property with that value but no other properties.