-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" : "[email protected]",
      "firstName" : "some",
      "lastName" : "user",
      "username" : "someuser"
    },
    "vyMiCS7olNPh9bCXoKWqcIFNWVy2" : {
      "email" : "[email protected]",
      "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
  }
}
8
  • You want to exchange uid with random number, right? Commented Mar 2, 2017 at 13:18
  • @Kinduser Yes, do you know how to do it? Commented Mar 2, 2017 at 13:18
  • Possible duplicate of Access JSON or JS property using string Commented Mar 2, 2017 at 13:21
  • So your problem is actually generating the random number or using it as a key after generating it? Commented Mar 2, 2017 at 13:22
  • 3
    Possible duplicate of JavaScript set object key by variable Commented Mar 2, 2017 at 13:24

7 Answers 7

1

Consider this code

var users = {}

users[ randomString(20) ] = {
    amount   : spentAmount,
    category : selectedCategory,
    date     : formattedDate,
    time     : formattedTime,
    note     : note
}
Sign up to request clarification or add additional context in comments.

Comments

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
}

1 Comment

Nice approach! Thanks!
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);

1 Comment

I am not asking how to generate random string :)
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);
}

4 Comments

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
@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 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 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 :)
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 ]

Comments

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/

Comments

-2
var temp = expensesObject[uid];
expensesObject[randomString(<length>)] = temp;

1 Comment

Welcome to Stack!! could you please provide us some explanation? thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.