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
Related
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)
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);
I want to duplicate an object in array in mongoose.
For example, if there is a object which projectName is "a", I want to create a complete same one, but the name is called "a duplicated".
I tried to the following code:
project.find({
"logininfo.username": username,
}, (err, users) => {
...
var user= users[0];
var dproject;
for(var i in user.projects){
if(user.projects[i].projectName === projectName)
{
dproject = user.projects[i];
break;
}
}
dproject.projectName += " duplicated";
dproject._id = new mongoose.Types.ObjectId();
user.projects.push(dproject)
projects.save((err, user) => {
...
However, this function will also change the previous object, which creates a completely same object (both names change to "a duplicated"), these two objects have the same _id.
How can I duplicate the object but keep the projectName and _id different?
Use JSON.parse(JSON.stringify(object)) to deep copy. It will make a copy but not a reference.
for (var i in projects.projects) {
if (projects.projects[i].projectName === projectName) {
dproject = JSON.parse(JSON.stringify(projects.projects[i])); //deep copy
break;
}
}
dproject._id = new mongoose.Types.ObjectId();
dproject.projectName += " duplicated";
projects.projects.push(dproject)
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' } ]
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'
}