0

I have these objects that reside in an array. I want to arrange them by key and display all values for one key at once.

[ { '18': 'x' },
  { '17': 'y' },
  { '17': 'z' },
  { '18': 'A' },
  { '18': 'B' },
  { '19': 'C' },
  { '19': 'D' },
  { '19': 'A' } ]

I want to display it eventually in my node.js app as:

17 -> y,z
18 -> X, A, B
19 -> C, D, A
1
  • 5
    Start with for + if. Then ask something more particular when you're in stuck Commented Oct 5, 2013 at 0:16

1 Answer 1

1
var hash={};
for (var i=0; i<a.length; i++) {
  for (var keys=Object.keys(a[i]), k=0; k<keys.length; k++) {
    var key = keys[k];
    console.log(key);
    if (hash[key]) {
      hash[key].push(a[i][key]);
    }
    else {
      hash[key]=[a[i][key]];
    }
  }
}

yields

"{
    "17": [
        "y",
        "z"
    ],
    "18": [
        "x",
        "A",
        "B"
    ],
    "19": [
        "C",
        "D",
        "A"
    ]
}"
Sign up to request clarification or add additional context in comments.

Comments

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.