1

So I have an object that has data in this form:

{key1: val1, key2: val2}

And I want to somehow convert to something like below:

{first: {key1:[], val1:[]},
second: {key2:[], val2:[]} };

I tried doing

object = {key1: val1, key2: val2};
var array = {};
var cc=0;
for (var prop in object){
    var ob_prop = object[prop];
    if(cc) array['first'] = {prop:[], ob_prop:[]};
    else array['second'] = {prop:[],ob_prop:[]};
    cc++;
}

but instead I get

{ second: { prop: [], ob_prop: [] },
first: { prop: [], ob_prop: [] } }
nonerth
  • 549
  • 2
  • 7
  • 19
  • I dont understand why I was down-voted, I explained clearly what I want and what I have tried. – nonerth Apr 06 '17 at 20:21
  • please add the source object and what you like to get from it. – Nina Scholz Apr 06 '17 at 20:23
  • 1
    I would assume the down vote may have been due to the lack of research. Posting should thoroughly research topic, then post what you have tried and/or found. In regards to your posting, perhaps the question was down voted because the answer can be found quite easily. In support of your comment, I think people should leave comments if they down vote. So here is one up vote for you. – SoEzPz Apr 06 '17 at 20:26
  • Thank you for the upvote! In my defense I should add I searched for an answer (perhaps I didnt do it right) and because I couldn't find, so I opened a question. – nonerth Apr 06 '17 at 20:28

1 Answers1

1

As mentioned in comments by Felix Kling, try: array['first'] = {[prop]:[], [ob_prop]:[]};

mateuszlewko
  • 1,110
  • 8
  • 18
  • nope that leads to a compilation error, as naturally it cant set property key1 of undefined. – nonerth Apr 06 '17 at 20:26
  • 3
    If you assume that the OP can use `for/of` loops, then using computed properties would probably be the simpler solution: `{[prop]:[], [ob_prop]:[]}`. – Felix Kling Apr 06 '17 at 20:27
  • Thank you, all I had to add was the `[`, `]` for it to work, so I guess indeed an idiotic question worthy of downvoting, so instead of `{prop:[], ob_prop:[]}` -> `{[prop]:[], [ob_prop]:[]}` – nonerth Apr 06 '17 at 20:29
  • 1
    Note that this is an ES6 feature, so older browsers may not support it. – Barmar Apr 06 '17 at 20:32
  • I'll keep that in mind thanks. – nonerth Apr 06 '17 at 20:34