Add an object to JSON - javascript

I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.

You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.

To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };

Related

Why does comparing a property to the author.id not work?

So here is my current code for a currency system. This code works to add the new user information in. Obviously this will keep adding the people that are already in it.
if (!currency[message.author.id]) {
currency.push({id: message.author.id, coins: 0});
}
if I change it to this one, nothing happens. It seems there's something wrong with this comparison and I'm not sure what it is considering it worked for other things I have used.
if (!currency[0].id == message.author.id) {
currency.push({id: message.author.id, coins: 0});
}
This looks right to me as it's getting the id property of the first element and checking if they're the same. When I run the code it just doesn't do anything. No errors and nothing in the json file I'm using to store it. It does this when the array is empty and does it when I have an id property in there.
Is this not possible? I don't like having to set it up using the first way because I'd like to be able to access everyone's currency if needed to add or take away without having to do it one person at a time.
I think it should be !==:
if (currency[0].id !== message.author.id) {
currency.push({id: message.author.id, coins: 0});
}
or should be wrapped in brackets:
if (!(currency[0].id == message.author.id)) {
currency.push({id: message.author.id, coins: 0});
}
It sounds like you probably want a data structure that's an object, not an array, so that you can have arbitrary key-value pairs - have the key be the message.author.id.
const currency = {};
// ...
const { id } = message.author;
if (!currency[id]) {
currency[id] = { id, coins: 0 };
} else {
// this author was already inserted - do something else here, if desired
// current[id].coins += coinChangeAmount; // for example
}
Your original code sounds like it's misusing an array as an object, and the currency[0].id == message.author.id will only check the [0]th element of the array, rather than iterating over all possible elements and looking for an ID match.

Javascript Equalize Element From Array

Guys I want to get an element from array. Here:
Follower:
{ follower:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
user id:
5edfe92fbfc9d677005d55cc
The process:
if(follower == user){
console.log("sdasdsad")
}else{
console.log("no")
}
But when I do it it always returns as no.
Also this is the codes of===> Nodejs Follow System Not Working Properly
It is a nodejs project. So please look at the above link.
When I do
if(follower.includes(user)){
It gives the error of:
TypeError: Cannot read property 'includes' of null
And when I try to change some I get this error:
TypeError: takip.includes is not a function
Guys so thats why I say please look at the above code.
So how to equalize them?
As other peoples said earlier the follower itself is a property which its value is an array itself, so if you want to check whether an item exists within it or not you can check it with includes(), if it exists it will return true otherwise it will return false.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if (follow.follower.includes(user)) {
console.log("sdasdsad")
} else {
console.log("no")
}
But if you looking to find the exact position of the item within that array you can find it with indexOf(). If the item does not exist within the array it will return -1, otherwise, it will return the index of that item within the array.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
console.log(follow.follower.indexOf(user));
You are trying to compare a string to an array so it will never pass the if statement.
If you change your if to be if ( follower.includes(user)) { then it will search the array for the string.
var follower = [
'5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
var user = '5edfe92fbfc9d677005d55cc'
// This will always fail as follower is an array not a string
if (follower.includes(user)){
console.log("sdasdsad")
} else {
console.log("no")
}
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Looks like follower is a property. You can use this solution:
objectName.follower.forEach(item =>
if (item == user) console.log(`${item} is the answer`);
);
This way, javascript will go through all of the elements in the array and print it out if it is matching with your user variable.
You can also use for loop or while loop for the same process, however, since you're using an array, forEach will be much more useful.
If this was not your question and I misunderstood your question, let me know, I'll see if I can help.
I hope this helps
var obj = {
follower: [ '5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
};
var userId = '5edfe92fbfc9d677005d55cc';
function searchUser(object, user){
if(obj.follower.includes(user)){
return object.follower.filter(x => x == user);
} else {
return 'no';
}
};
console.log(searchUser(obj, userId));
You can use Array.protorype.some() to check if user exists in the follower array.
const obj = {
follower: [
"5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if(obj.follower.some(item => item === user)) {
console.log("found")
} else{
console.log("no")
}
You can also get the item with Array.protorype.find() with the same way as above, just assign it to a variable
Array.prototype.some
Array.prototype.find

How to have an object key depend on another key in the same object?

I have a very simple function that builds an object and logs it.
One of the keys in the object should be depending on another key.
I think it would be much clearer when I add the code
module.exports = function (information) {
var numObj = {
[-1]: "accepted",
[0]: "fail",
[1]: "success"
}
console.log(numObj)
var ip = require('ip');
var logObj = {
UUID: information.UUID, // get from outside
FN_TIME_STAMP: information.FN_TIME_STAMP, // not sure if necessary
FN_CORRELATION_ID: information.FN_CORRELATION_ID,// get from outside
FN_REF_ID: information.FN_REF_ID, //get from outside
FN_METHOD_NAME: "docToMail", // constant
FN_STATUS_CODE: information.FN_STATUS_CODE, //get from outside
FN_STATUS_DESC: numObj[this.FN_STATUS_CODE], // depends on FN_STATUS_CODE
FN_DOC_ID: information.FN_DOC_ID, //get from outside
FN_USER_NAME: "", // empty for now, probably un-necessary
FN_APP_ID: information.FN_APP_ID, //get from outside
FN_RMT_ADDRS: ip.address(),//ip address of local machine
FN_NUM_OF_RETRIES: information.FN_NUM_OF_RETRIES, // get from outside
FN_FILETYPE: information.FN_FILETYPE, // get from outside
FN_REC_STATE: numObj[this.FN_STATUS_CODE] //depends on FN_STATUS_CODE
}
console.log(logObj)
}
I just want FN_REC_STATE and FN_STATUS_DESC to be a string depending on FN_STATUS CODE.
If its -1 i want the string to be "accepted"
If its 0 i want the string to be "fail"
If its 1 i want the string to be "success"
as it as right now i just get undefined, please help!
Thanks
Assuming that information.FN_STATUS_CODE is either -1, 0 or 1, the following solution should work.
If you change
FN_REC_STATE: numObj[this.FN_STATUS_CODE]
to
FN_REC_STATE: numObj[information.FN_STATUS_CODE]
then it should put the correct value into FN_REC_STATE.
This is because by the time that faulty line is evaluated, this.FN_STATUS_CODE hasn't been defined.
You should also change this for the definition of FN_STATUS_DESC.
Also, it looks like you may be misunderstanding what this refers to in the context of that function. It actually refers to the global object, rather than the logObj object.

How do I set a JavaScript object's value to null

I have created this JS object from an array.
var rv = {};
$( ".part-name:visible" ).each(function( index ) {
//rv[$(this).text()] = arrayPartsName[$(this).text()];
rv[$(this).text()] = arrayPartsName[$(this).text()];
console.log(rv);
})
4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"
I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this
4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null
How can do this?
Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic
But to focus on your specific question:
Change this line
rv[$(this).text()] = arrayPartsName[$(this).text()];
to
rv[$(this).text()] = null;
Something to be aware of
If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().
var fruit = {
"pear": null, // something null
"talk": function() { console.log('WOOHOO!'); } // function
}
var apple = "app-le";
fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';
// below is not allowed, the values will be evaluated as
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';
fruit.talk();
console.log(fruit);

How can I compare a string to an object key and get that key's value?

I want to do something relatively simple, I think anyways.
I need to compare the pathname of page with an object's kv pairs. For example:
if("pathname" === "key"){return value;}
That's pretty much it. I'm not sure how to do it in either regular Javascript or jQuery. Either are acceptable.
You can see my fiddle here: http://jsfiddle.net/lz430/2rhds1x3/
JavaScript:
var pageID = "/electrical-electronic-tape/c/864";
var pageList = [{
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
}];
var label = pageID in pageList;
$('.el').html(label);
First, your "pageList" should just be a plain object, not an object in an array:
var pageList = {
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
};
Then you can set "label" to the value from the mapping:
var label = pageList[pageID] || "(not found)";
That last bit of the statement above will set the label to "(not found)" if the lookup fails, which may or may not be applicable to your situation.
It depends kinda on the logic you want to implement. If you want to say "if object has the key, then do X, and if not, then do Y", then you handle that differently than "set label to the object's key's value if the key is there, or else set it to undefined or something else".
For the first case you do:
if (pageList.hasOwnProperty(pageID) ) {
label = pageList[pageID];
}
else {
// do whatever, maybe some error?
}
For the second case, you can just say
var label = pageList[pageID] || 'notFound';
As indicated by #Pointy, either get rid of the array or subsiture pageList[0] for pageList and pageList[0][pageID] for pageList[pageID] above, if you need to keep the array.

Categories

Resources