-1

I am trying to create a JSON object, with a random string as the name, just like how Firebase does it.

Goal: replace child name with random string.

For example:

"Users" : {
    "mGKgNDOw0qd77m6tmdDh76zOQOm2" : {
      "email" : "someuser@gmail.com",
      "firstName" : "some",
      "lastName" : "user",
      "username" : "someuser"
    },
    "vyMiCS7olNPh9bCXoKWqcIFNWVy2" : {
      "email" : "someuser2@gmail.com",
      "firstName" : "some",
      "lastName" : "user2",
      "username" : "someuser2"
    }
}

This is what I got so far, I manage to get my head around with a string randomise function.

randomString(length) {
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

And I would like to push my data into the object with random string as the name.

I tried string interpolation but it does not work.

var expensesObject = {
  uid: {
    amount: spentAmount,
    category: selectedCategory,
    date: formattedDate,
    time: formattedTime,
    note: note
  }
}
J.Doe
  • 1,097
  • 1
  • 16
  • 34
  • You want to exchange `uid` with random number, right? – kind user Mar 02 '17 at 13:18
  • @Kinduser Yes, do you know how to do it? – J.Doe Mar 02 '17 at 13:18
  • Possible duplicate of [Access JSON or JS property using string](http://stackoverflow.com/questions/7027051/access-json-or-js-property-using-string) – JAAulde Mar 02 '17 at 13:21
  • So your problem is actually generating the random number or using it as a key after generating it? – Alejandro Iván Mar 02 '17 at 13:22
  • 3
    Possible duplicate of [JavaScript set object key by variable](http://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) – Mehdi Mar 02 '17 at 13:24
  • @AlejandroIván my problem is to replace child name with random string – J.Doe Mar 02 '17 at 13:26
  • If your array is already generated and already has a `uid` key, you could: 1) Generate the random string `var randomString = ...;` (you already got this). 2) Get the `uid` data from the array `var data = Users['uid'];` 3) Remove the `uid` key from the array `Users.splice('uid', 1);` 4) Re-add the data with its new key `Users[randomString] = data;` – Alejandro Iván Mar 02 '17 at 13:29
  • If the array isn't generated yet, just: 1) Generate your random string `var randomString = ...;` 2) Generate your array using it as a key `var Users = { randomString: { ... }};` **EDIT:** Okay this last syntax I'm not completely sure it will work, so you could do `var Users = {};` and then `Users[randomString] = { ... };` and it will work for sure. – Alejandro Iván Mar 02 '17 at 13:30

7 Answers7

1

You can do this by setting directly the object's key using []:

var expensesObject = {}

expensesObject[uid] = {
    amount: spentAmount,
    category: selectedCategory,
    date: formattedDate,
    time: formattedTime,
    note: note
}
Mehdi
  • 7,204
  • 1
  • 32
  • 44
1

Consider this code

var users = {}

users[ randomString(20) ] = {
    amount   : spentAmount,
    category : selectedCategory,
    date     : formattedDate,
    time     : formattedTime,
    note     : note
}
1

You could use a single random number for a distinct place. The check if lower or upper case.

Then assign to the new key the property of uid and delete the property.

function replaceUID(object) {
    object[random(28)] = object.uid;
    delete object.uid;
}

function random(size) {
    var r, s = '';
    while (s.length < size) {
        r = Math.floor(Math.random() * 62);
        s += r >= 36 ? (r - 26).toString(36).toUpperCase() : r.toString(36);
    }
    return s;
}

var expensesObject = { uid: { amount: 'spentAmount', category: 'selectedCategory',
date: 'formattedDate', time: 'formattedTime', note: 'note' } };

replaceUID(expensesObject);
console.log(expensesObject);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Copy the object uid to a new object containing the random string

var expensesObject = {
  uid: {
    amount: 5,
    category: "catA",
    date: "02-03-2017",
    time: "14:00:00",
    note: "Notes"
  }
};

var finalobject = {};
let propertyName = randomString(10); //get the random string
finalobject[propertyName] = expensesObject.uid; //copy uid object
console.log(finalobject);

function randomString(length) {
  return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • I don't think the OP meant to literally replace `uid` as an existing property name on an existing object. The object in the final code sample is just an example of desired output – JAAulde Mar 02 '17 at 13:22
  • @Weedoze this is exactly what I'm looking for! Would the performance be dropping if we are to copy uid object? I'm dealing with large data set – J.Doe Mar 02 '17 at 13:28
  • @J.Doe You can try it yourself but I think that it won't be slow. What do you call *large* ? Don't forget to upvote the answer or mark it if it solved your problem – Weedoze Mar 02 '17 at 13:31
  • @Weedoze I'm trying an expenses app whereby users would add expenses object everyday. Will accept your answer in a sec, SO doesn't let me do that just yet :) – J.Doe Mar 02 '17 at 13:33
0

You could do something like this:

function randomString(length) {
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

var keylength = 16;  // <-- change as needed

var myObject = {
    amount: spentAmount,
    category: selectedCategory,
    date: formattedDate,
    time: formattedTime,
    note: note
  }

var expensesObject = {};

var uuid = randomString(keylength);

expensesObject[uuid]=myObject; // <-- use [ var_name ]
mvermand
  • 5,829
  • 7
  • 48
  • 74
0

You also can create string and convert it to JSON object like this:

var expensesObjectStr = "{"+ '"'+ uid+'"'+": {"+
    '"amount"'+":"+ spentAmount+","+
    '"category"'+":"+'"'+ selectedCategory+'"'+","+
    '"date"'+": "+'"'+ formattedDate+'"'+","+
    '"time"'+": "+'"'+ formattedTime+'"'+","+
    '"note"'+": "+'"'+ note+'"'+
  "} }";

var obj = jQuery.parseJSON(expensesObjectStr);

Here small fiddle - https://jsfiddle.net/skyr9999/2dvffaty/

Vasilij Altunin
  • 754
  • 1
  • 5
  • 18
-2
var temp = expensesObject[uid];
expensesObject[randomString(<length>)] = temp;
Vadym Buhaiov
  • 167
  • 1
  • 15