node js access value in json result and get the value - node.js

i have following json object which i get from API end point
let myjson = { Team1: { SCORE: 10 } }
i want to access the score inside Team but not able to complete as i need to just the result as 10
i have tried following code but not able to get the result
for(var attribute name in JSON.parse(myjson)){
return console.log(attributename+": "+body[attributename]);
}
i also used bellow code
const userStr = JSON.stringify(myjson);
JSON.parse(userStr, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});

Not a node developer but why do you need to json.stringify it? Can't you just reach the value with dot notation like this:
myJson.Team1.SCORE

myjson is already an Object, you don't need to do JSON.parse nor JSON.stringify on it.
Just access the property directly:
console.log(myjson.Team1.SCORE)
If you have multiple teams, or want to access it dynamically:
const obj = { Team1: { SCORE: 10 }, Team2: { SCORE: 20 } }
for(const [team, value] of Object.entries(obj)) {
console.log(`${team}: ${value.SCORE}`)
}

you also can use this if it fulfills your query.
here is the code.
let myjson = {Team1: {SCORE:10}, Team2: {SCORE: 20}};
Object.keys(myjson).forEach(function(item) {
console.log(myjson[item].SCORE);
});

Not sure if there can be more teams in that object, so I put here some more complex solution and then the straightforward one.
const myjson = { Team1: { SCORE: 10 }, Team2: { SCORE: 20 } }
const result = Object.keys(myjson).map(key => myjson[key].SCORE);
console.log('For dynamic resolution', result);
console.log('If there is only Team1', myjson.Team1.SCORE);

Related

Dot notation vs. Bracket Notation

Why does dot notation not delete the key using javascript but bracket notation does?
function removeProperty(obj, key) {
// your code here
delete obj.key;
}
var obj = {
name: 'Sam',
age: 20
}
console.log(obj.name);
removeProperty(obj, 'name');
console.log(obj.name); // --> undefined
The question is frankly bit unclear but I will try to answer it based on my understanding
To delete a key from object we do something like this
var obj = {
name: 'Sam',
age: 20
}
delete obj.name
console.log(obj) // won't have name
Now In your function,
function removeProperty(obj, key) {
// your code here
delete obj.key;
}
You are trying to delete a property key from obj which does not exist.
Correct way would've been
function removeProperty(obj, key) {
// your code here
delete obj[key]
}
So, the correct way to delete inside a function in case of your code snippet would be
function removeProperty(obj, key) {
// your code here
delete obj[key];
}
var obj = {
name: 'Sam',
age: 20
}
console.log(obj.name);
removeProperty(obj, 'name');
console.log(obj.name); // --> undefined

Get map of map field from Firestore

I have a field of type map that contains Maps of data in firestore.
I am trying to retrieve this data using a cloud function in node.js. I can get the document and the data from the field but i can't get it in a usable way. I have tried every solution i can find on SO and google but the below is the only code that can give me access to the data. I obviously need to be able to access each field with in the Map individually. in swift i build an array of String:Any but i can get that to work in Node.JS
const docRef = dbConst.collection('Comps').doc('XEVDk6e4AXZPkNprQRn5Imfcsah11598092006.724980');
return docRef.get().then(docSnap => {
const tagets = docSnap.get('targets')
console.log(tagets);
}).catch(result => { console.log(result) });
this is what i am getting back in the console.
In Swift i do the following and am so far not able to find an equivalent in typescript. (i don't need to build the custom object just ability to access the keys and values)
let obj1 = doc.get("targets") as! [String:Any]
for objs in obj1{
let obs = objs.value as! [String:Any]
let targObj = compUserDetails(IDString: objs.key, activTarg: obs["ActivTarget"] as! Double, stepTarg: obs["StepTarget"] as! Double, name: obs["FullName"] as! String)
UPDATE
After spending a whole day working on it thought i had a solution using the below:
const docRef = dbConst.collection('Comps').doc('XEVDk6e4AXZPkNprQRn5Imfcsah11598092006.724980');
return docRef.get().then(docSnap => {
const tagets = docSnap.get('targets') as [[string, any]];
const newDataMap = [];
for (let [key, value] of Object.entries(tagets)) {
const tempMap = new Map<String,any>();
console.log(key);
const newreWorked = value;
tempMap.set('uid',key);
for(let [key1, value1] of Object.entries(newreWorked)){
tempMap.set(key1,value1);
newDatMap.push(tempMap);
};
};
newDatMap.forEach(element => {
const name = element.get('FullName');
console.log(name);
});
However the new data map has 6 seperate mapped objects. 3 of each of the original objects from the cloud. i can now iterate through and get the data for a given key but i have 3 times as many objects.
So after two days of searching an getting very close i finnaly worked out a solution, it is very similar to the code above but this works. it may not be the "correct" way but it works. feel free to make other suggestions.
return docRef.get().then(docSnap => {
const tagets = docSnap.get('targets') as [[string, any]];
const newDatarray = [];
for (let [key, value] of Object.entries(tagets)) {
const tempMap = new Map<String,any>();
const newreWorked = value;
tempMap.set('uid',key);
for(let [key1, value1] of Object.entries(newreWorked)){
tempMap.set(key1,value1);
};
newDatarray.push(tempMap);
};
newDatarray.forEach(element => {
const name = element.get('FullName');
const steps = element.get('StepTarget');
const avtiv = element.get('ActivTarget');
const UID = element.get('uid');
console.log(name);
console.log(steps);
console.log(avtiv);
console.log(UID);
});
}).catch(result => { console.log(result) });
I made this into a little function that gets the underlying object from a map:
function getMappedValues(map) {
var tempMap = {};
for (const [key, value] of Object.entries(map)) {
tempMap[key] = value;
}
return tempMap;
}
For an object with an array of maps in firestore, you can get the value of the first of those maps like so:
let doc = { // Example firestore document data
items: {
0: {
id: "1",
sr: "A",
},
1: {
id: "2",
sr: "B",
},
2: {
id: "3",
sr: "B",
},
},
};
console.log(getMappedValues(doc.items[0]));
which would read { id: '1', sr: 'A' }

Json/Nodejs: How do I get specific data from a JSON file

I am trying to develop a discord bot with nodejs. My question is how do I get a specific data out of a JSON file (for instance, from this json. I want to only specify a single uuid like "59d4c622c7cc459a98c2e947054e2b11" and get the data.
Assuming you have already parsed the JSON into an actual Javascript object named data and given the way the data is currently organized, you would have to search the data.guild.members array to find the object that had the desired uuid property value.
function findDataForUuid(uuid) {
for (let obj of data.guild.members) {
if (obj.uuid === uuid) {
return obj;
}
}
// no match found
return null;
}
let item = findDataForUuid("59d4c622c7cc459a98c2e947054e2b11");
if (item) {
console.log(item); // will show all the properties of the member object
}
Or, using .find() on the array:
function findDataForUuid(uuid) {
return data.guild.members.find(item => {
return item.uuid === uuid;
});
}
The simple soln you can use filter. Best is use reduce.
const data = {
guild: {
_id: "5b2906070cf29ddccd0f203c",
name: "Dulcet",
coins: 122010,
coinsEver: 232010,
created: 1529415175560,
members: [
{
uuid: "59d4c622c7cc459a98c2e947054e2b11",
rank: "MEMBER",
joined: 1529683128302,
questParticipation: 39,
expHistory: {
"2020-02-16": 0,
"2020-02-15": 0,
"2020-02-14": 0,
"2020-02-13": 0,
"2020-02-12": 0,
"2020-02-11": 0,
"2020-02-10": 0
}
}
]
}
};
const members = data.guild.members.filter(
member => member.uuid == "59d4c622c7cc459a98c2e947054e2b11"
);
const firstMember = members[0]
console.log(firstMember)

array manipulation in node js and lodash

I have two arrays
typeArr = [1010111,23342344]
infoArr={'name':'jon,'age':25}
I am expecting following
[{'name:'jone','age':25,'type':1010111,'default':'ok'},{'name:'jone','age':25,'type':23342344,'default':'nok'}]
Code :
updaterecord(infoArr,type)
{
infoArr.type=type;
response = calculate(age);
if(response)
infoArr.default = 'ok';
else
infoArr.default = 'nok';
return infoArr;
}
createRecord(infoArr,typeArr)
{
var data = _.map(typeArr, type => {
return updaterecord(infoArr,type);
});
return (data);
}
var myData = createRecord(infoArr,typeArr);
I am getting
[{'name:'jone,'age':25.'type':23342344,'default':nok},{'name:'jone,'age':25.'type':23342344,'default':nok}]
with some reason the last record updates the previous one. I have tried generating array using index var but not sure what's wrong it keep overriding the previous item.
how can I resolve this
You are passing the entire infoArr array to your updaterecord() function, but updaterecord() looks like it's expecting a single object. As a result it is adding those properties to the array rather than individual members of the array.
It's not really clear what is supposed to happen because typeArr has two elements and infoArr has one. Do you want to add another to infoArr or should infoArr have the same number of elements as typeArr.
Assuming it should have the same number you would need to use the index the _map gives you to send each item from infoArr:
function createRecord(infoArr,typeArr) {
var data = _.map(typeArr, (type, i) => {
// use infoArr[i] to send one element
return updaterecord(infoArr[i],type);
});
return (data);
}
Edit:
I'm not sure how you are calculating default since it's different in your expected output, but based on one number. To get an array of objects based on infoArray you need to copy the object and add the additional properties the you want. Object.assign() is good for this:
let typeArr = [1010111,23342344]
let infoArr={'name':'jon','age':25}
function updaterecord(infoArr,type){
var obj = Object.assign({}, infoArr)
return Object.assign(obj, {
type: type,
default: infoArr.age > 25 ? 'ok' : 'nok' //or however your figuring this out
})
}
function createRecord(infoArr,typeArr) {
return _.map(typeArr, type => updaterecord(infoArr,type));
}
Result:
[ { name: 'jon', age: 25, type: 1010111, default: 'nok' },
{ name: 'jon', age: 25, type: 23342344, default: 'nok' } ]

Dynamically change elasticsearch query definition

So I am trying to dynamically delete specific documents from elastic and would like to use one function without hard coding the name of the item I am looking for the time range in. See code below:
exports.cleanElastic = function(type, timeReference){
return new Promise (function (resolve, reject){
let dataOlderThan = "now-".concat(config.amountOfData);
elastic.deleteByQuery({
index: 'canary',
type: type,
body: {
query: {
range : {
START_TS: {
lte: dataOlderThan
}
}
}
}
},
As you can see 'START_TS' is the name of the date field I care about in this instance. That will not always be the case with the project. So I am trying to pass 'timeReference' or at least its' value in for where the query reads 'START_TS'. Any suggestions would be much appreciated.
Thank you,
Ryan
I think what you are asking is more of javascript to convert strings to symbols.
exports.cleanElastic = function(type, timeReference){
return new Promise (function (resolve, reject){
let dataOlderThan = "now-".concat(config.amountOfData);
elastic.deleteByQuery({
index: 'canary',
type: type,
body: {
query: {
range : {
toSymbol(timeReference): {
lte: dataOlderThan
}
}
}
}
}
}
}
function toSymbol(variable) {
return Symbol(variable);
};
In rails we use something like following for this.
key_name = 'age'
hash = {
name: 'john',
key_name.to_sym => '23'
}

Resources