Changing the JSON key and keeping its index same - javascript

I want to change the key of JSON attribute and keep/persist its position/Index.
E.g.
{"Test1" : {
mytest1:34,
mytest2:56,
mytest6:58,
mytest5:89,
}
}
Now I want to change the key mytest6 to mytest4 and keep its position as it is.
Note: In my case I can't use Array.
Thanks.

jsonObj = {"Test1" : {
mytest1:34,
mytest2:56,
mytest6:58,
mytest5:89,
}
};
var old_key = "mytest6";
var new_key = "mytest4";
if (old_key !== new_key) {
Object.defineProperty(jsonObj.Test1, new_key,
Object.getOwnPropertyDescriptor(jsonObj.Test1, old_key));
delete jsonObj.Test1[old_key];
}
console.log(jsonObj);
This method ensures that the renamed property behaves identically to the original one.
Also, it seems to me that the possibility to wrap this into a function/method and put it into Object.prototype is irrelevant regarding your question.
Fiddle

Related

Pass object and properties by reference in Javascript

I've seen lots of questions about passing objects by reference in Javascript, but not the object and properties by reference. Is it possible?
Right now I only found a way to do it by going through some type of logic like this, which is terribly inconvenient:
let multipliers = {
none:1,
sin:2,
cos:3,
tan:4,
atan:5,
}
incMultiplier(shapesMovements[index], "rotation", "x", "sin")
function incMultiplier(shapeMovement, kind, dimension, multiplier){
var numOfKeys = Object.keys(multipliers).length;
if(kind === "rotation"){
if(dimension === "x"){
if(multiplier === "sin"){
if(shapeMovement.rotation.x.multiplier !== numOfKeys){
shapeMovement.rotation.x.multiplier += 1
}else{
shapeMovement.rotation.x.multiplier = 1
}
}
}
}
}
I'd just like to increase the property value by one with whatever object and property I've thrown into that function.
I've seen another post where you can pass parameters, but this looks to assemble a new object, and is not by reference. I need to actually edit the values on the object's properties.
Originally, this is what I was trying, and it did not seem to alter the object on a global level. Only locally to the function:
incMultiplier(shapesMovements[index].rotation.x.multiplier)
function incMultiplier(multiplier){
var numOfKeys = Object.keys(multipliers).length;
if(multiplier !== numOfKeys){
multiplier = multiplier + 1
}else{
multiplier = 1
}
// always results in the same number.
// Does not keep increasing every time the function is called.
console.log(multiplier);
}
Originally, this is what I was trying
You're not passing an object with its properties there. You're passing the value of a single property, and assignments to multiplier do indeed just overwrite the local variable in the function. You need to pass an object and explicitly assign to its property:
function incMultiplier(valueObj) {
var numOfKeys = Object.keys(multipliers).length;
if (valueObj.multiplier !== numOfKeys) {
valueObj.multiplier++;
} else {
valueObj.multiplier = 1
}
}
incMultiplier(shapesMovements[index].rotation.x)
incMultiplier(shapesMovements[index].position.x)
incMultiplier(shapesMovements[index].rotation.y)
incMultiplier(shapesMovements[index].rotation.z)
It's not necessary to pass the whole shapesMovements objects and everything nested within them, passing a single mutable object is enough.

Add an object to JSON

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 };

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.

jquery how to collect all link value from a object?

i have a object, just i need to collect and store the object which contains the lable as link in to a new array.. can any one give me the best way to do this?
myobeject:
var xploreMaps = {
radious:55,
stroke:5,strokeColor:'#fff',
opacity:0.8,fontSize:13,line:10,
cRtext:{
length:4,
lineColor:'#7d2c2c',
prop:{
0:{link:'motionGraphics.html',color:'#595959',text:'Motion Graphics'},
1:{link:'video.html',color:'#306465',text:'Video'},
2:{link:'photography.html',color:'#7e6931',text:'Photography'},
3:{link:'copyRight.html',color:'#4c4966',text:'Copywriting'}
}
},
cBtext:{
length:3,
lineColor:'#4c839d',
prop:{
0:{link:'imagination.html',color:'#595959',text:'Imagination'},
1:{link:'innovation.html',color:'#306465',text:'Innovation'},
2:{link:'ideation.html',color:'#7e6931',text:'Ideation'}
}
},
cGtext:{
length:5,
lineColor:'#579549',
prop:{
0:{link:'catalogs .html',color:'#7a5967',text:'Catalogs',
subLink:{0:{link:'SEO_SMM.html',color:'#4e4b69',text:'SEO/SMM',align:'top'},1:{link:'site_analytics.html',color:'#545454',text:'Site analytics',align:'btm'}}},
1:{link:'socialmedia.html',color:'#1e9ead',text:'Innovation'},
2:{link:'loyalty .html',color:'#8fad34',text:'Ideation'},
3:{link:'promotions .html',color:'#563b64',text:'Promotions'},
4:{link:'implementations.html',color:'#2c6566',text:'Implementations',
subLink:{0:{link:'integrating.html',color:'#4c4a66',text:'Integrating',align:'top'},1:{link:'payment.html',color:'#948048',text:'Payment',align:'btm'}}}
}
}
}
My function which i try:
var links = []//just i need all the objects which contains the link.
var objFinder = function (obj){
$.each(obj,function(key,val){
if(key == 'link' && typeof val == 'string'){
links.push(val)
}else{
objFinder(val);//throws errors;
}
})
}
objFinder(xploreMaps);
}
I think the main issue is that your objects have a property length. That is messing up the processing. See the fiddle I created here:
http://jsfiddle.net/8Zfdj/
I just commented out the length property and it seems to work properly. I also did some minor cleanup such as adding missing semi-colons but that wasn't the main issue.
You can see the jQuery bug (invalid) here:
http://bugs.jquery.com/ticket/7260

Categories

Resources