1

I have heard that JavaScript does not support associative arrays. Is it true?

I mean:

assocArray = [
  {a: ""},
  {b: ""},
  {c: ""}
];

How do I get the keys of the above assocArray?

I tried using:

for (each in assocArray) {}

But it gives: 0, 1, 2

1
  • assocArray.map(item => Object.keys(item)[0]) Commented Oct 29, 2019 at 9:53

4 Answers 4

5

You can try with flatMap()

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

and Object.keys()

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

var assocArray = [{a : "" },{b : ""},{c : ""}]; 
var keys = assocArray.flatMap(i => Object.keys(i));
console.log(keys);

Sign up to request clarification or add additional context in comments.

1 Comment

map + flat = flatmap
1

Try to use the spread operator and the Object.keys method:

let assocArray = [{a : "" },{b : ""},{c : ""}];

let oneObject = Object.assign({}, ...assocArray);
let keys = Object.keys(oneObject);

console.log(keys);

Comments

1

If you want to loop through the objects of your array, you can use the following.

for(index in assocArray){
    assocArray[index]
}

But, I have the feeling that you should use a dictionary:

assocArray = {a : "" , b : "" , c : "" };

And then, loop through it

for (var key in assocArray) {

    // Skip loop if the property is from prototype
    if (!assocArray.hasOwnProperty(key)) continue;

    var obj = assocArray[key];
}

Comments

1

assocArray = [{a : "" }, {b : ""}, {c : ""}];

for(each in assocArray){
  console.log(each); // Each is actually the index
  console.log(assocArray[each]); // The item at index 'each'
  console.log(Object.keys(assocArray[each])[0]); // The first of the keys of the object at index 'each'
}

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.