0

I have object like this:

{
"first" : "value1",
"second" : "value2"
}

I want to access both values in for cycle. Order of getting values doesn't mind. Usage is for something like value = value + "something". How to acces values which key names I don't know? Of course I can get keys from helping array like:

var keys = ["first", "second"];

And then get them by index and with them get value1 and value2 from my original array. Is there some better way? For some reason foreach doesn't work either.

Barmar
  • 741,623
  • 53
  • 500
  • 612
FoksaK
  • 121
  • 1
  • 9
  • 2
    The array at the top of the question is not JavaScript syntax. – Pointy Apr 08 '21 at 19:18
  • 1
    You should clarify what you want here. You are showing square brackets `[]`, which means array, but `=>` is not valid within an array and arrays don't have "keys". Objects, on the other hand do have "keys"`. – Scott Marcus Apr 08 '21 at 19:18
  • 2
    You can use `Object.keys()` to get the keys, loop over that. You can slso use `Object.values()` to get the values, and `Object.entries()` to get both together. – Barmar Apr 08 '21 at 19:19
  • Thank you for replies. My solution is understanding the datatype like object. – FoksaK Apr 08 '21 at 19:22

3 Answers3

1

Javascript has a for ... in to loop through keys

for (var key in object) {
   console.log(object[key])
}
TSR
  • 17,242
  • 27
  • 93
  • 197
  • Thank you. Your solution seems profesional. Getting keys in for cycle is really interesting functionality of js. – FoksaK Apr 08 '21 at 19:31
1

To access both values:

const data = {
  "first": "value1",
  "second": "value2"
};

// (1) for-loop

for (const [key, value] of Object.entries(data)) {
  console.log("for-loop:", key, value);
}

// (2) Array.prototype.forEach

Object.entries(data).forEach(([key, value]) => {
  console.log("Array.prototype.forEach:", key, value);
});
Anson Miu
  • 1,171
  • 7
  • 6
1

If you just want the keys and values separately in an array you can do the following:

var data = {
"first" : "value1",
"second" : "value2"
}
var keys = Object.keys(data)
var values = Object.values(values)

Printing them out individually would give you:

console.log(keys)
Output: ["first", "second"]

console.log(values)
Output: ["value1", "value2"]
anisoleanime
  • 409
  • 3
  • 10