Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>[[The first part of this answer is based on a previous version of the OP's question which has now been edited to a different problem. See the second part of this answer for the solution which applies to the current edit of the question (It really messes things up when the whole question gets changed to something else.]]</p> <h2>Original Answer</h2> <p>You just have to test if the key already exists and examine if there's already an array there. If the key doesn't exist, add it. If the key exists and it's already an array, just push another value into the array. If the key exists, but it's not an array, grab the value and then reset the key to an array with the first two values in it.</p> <p>Here's code to do that:</p> <pre><code>function addValue(obj, key, value) { if (obj.hasOwnProperty(key)) { // check if it's already an array using the recommended way of detecting an array if (Object.prototype.toString.call(obj[key]) === "[object Array]") obj[key].push(value); } else { var firstVal = obj[key]; obj[key] = [firstVal, value]; } } else { obj[key] = value; } } </code></pre> <hr> <h2>Latest Answer</h2> <p>FYI, your data structure choice is difficult to both read and write because both reader and writer have to check the type of a value before they can operate on it. It would be much easier if items were just always arrays with one or more elements in them like this.</p> <pre><code>// one item for each key A = {"room1":["1"], "room2":["2"], "room3":["3"]}; // add 101 to room 1 A = {"room1":["1","101"], "room2:["2"], "room3":["3"]}; // add 201 to room 2 A = {"room1":["1","101"], "room2":["2","201"], "room3":["3"]}; </code></pre> <p>Then, you would need any special code to read and to write, you'd just check if the key exists and if so, push a new value into it. If not, add the array.</p> <p>In this case, adding a value would just be this</p> <pre><code>function addValue(obj, key, value) { if (obj.hasOwnProperty(key)) { obj[key].push(value); } else { obj[key] = [value]; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload