Search code examples
javascriptarrayskeyassociative

Single array to multiple array javascript


y have an array associative and want to save multiple arrays with only one key value like that:

[
  key1: value1,
  key2: value2,
  key3: value3
]

[ key1: value1 ]
[ key2: value2 ]
[ key3: value3 ]

Solution

  • Associative Arrays are the same as Objects in JavaScript and most everyone I know of refers to them "Objects", not "Associative Arrays" (within the context of JavaScript). This answer will also refer to Associative Arrays as Objects.

    None of the objects in your question are valid.
    You need to wrap object literals in curly braces, not square ones (square brackets are for array literals). You need to assign them to a variable (or pass them as a parameter, or have a return keyword in front of them, et. al).

    I'm assuming that the object you want to turn into multiple objects is your first example, and that the second example is what it should look like when it's done. Here are your examples, rewritten to match that assumption.

    // assign it to a variable
    var firstExample = {
      key1: 'value1',   // dunno if value1, 2, or 3 are strings, but stringifying them works for an example
      key2: 'value2',
      key3: 'value3'
    };
    
    var secondExample = [   // I assume you want an array of objects, each with a single key/value pair.
        { key1: 'value1' },
        { key2: 'value2' },
        { key3: 'value3' },
    ];
    

    That said, the easiest method I can think of to accomplish what you're looking for is to get the keys of your object and then loop through them and map them to individual objects.

    var firstExample = {
      key1: 'value1',
      key2: 'value2',
      key3: 'value3'
    };
    
    var secondExample = [
        { key1: 'value1' },
        { key2: 'value2' },
        { key3: 'value3' },
    ];
    
    // ES6 syntax
    const arrayOfObjects = Object.keys(firstExample).map(key => ( { [key]: firstExample[key] } ));
    
    console.log('Array of objects', arrayOfObjects);
    console.log('arrayOfObjects is equivalent to secondExample:', JSON.stringify(arrayOfObjects) === JSON.stringify(secondExample));
    
    // ES5 syntax
    var es5 = Object.keys(firstExample).map(function (key) {
        var o = {};
        o[key] = firstExample[key];
        return o;
    });
    
    console.log('ES5-syntax array of objects', es5);
    console.log('es5 is equivalent to secondExample:', JSON.stringify(es5) === JSON.stringify(secondExample));