1

I have valid JSON data as :

{
 "bitcoin": [
    "-0.47",
    "-0.46",
    "-0.42"
 ],
 "maker": [
    "8.29",
    "8.29",
    "6.89"
 ]
}

How can I get values from such data where there is no key?

Edit: with the help of @kolzar and @FZs, I simply managed it by following code:

for (var key in obj) {
  console.log(key + obj[key]);
}
Haseeb Hassy
  • 522
  • 8
  • 20

3 Answers3

1

In arrays ([...]), keys are numbers.
In JS, you can access properties two ways:

  • container[key_as_expression] or
  • container.key_as_identifier

Since JS identifiers don't allow to an identifier begin with a number, number keys can only be accessed through the first way:

data={
 "bitcoin": [
    "-0.47",
    "-0.46",
    "-0.42"
 ],
 "maker": [
    "8.29",
    "8.29",
    "6.89"
 ]
}

console.log(data.bitcoin[0]) //"-0.47"
console.log(data.bitcoin[1]) //"-0.46"

Since the first syntax allows expressions, the key must not hard-coded:

n=0
data={
 "bitcoin": [
    "-0.47",
    "-0.46",
    "-0.42"
 ],
 "maker": [
    "8.29",
    "8.29",
    "6.89"
 ]
}

console.log(data.bitcoin[n]) //"-0.47"
console.log(data.bitcoin[n+1]) //"-0.46"

And there are a lot of loops, which can help you:

  • for - The most commonly used loop. To execute something on all elements of an array:

    data=[1,2,3,"hello","world"]
    
    for(let i=0;i<data.length;i++){
      console.log(i,data[i])
    }
  • for of - More simple syntax, but keys are unavailable. Example:

    data=[1,2,3,"hello","world"]
    
    for(let x of data){
      console.log(x)
    }
  • array.forEach - Execute a function on all elements of an array:

    data=[1,2,3,"hello","world"]
    
    data.forEach(function(x,i){console.log(i,x)})

And many more similar options!

FZs
  • 16,581
  • 13
  • 41
  • 50
  • Thank you for pointing me in a direction. but I have 100s of such arrays with alot of items inside them and can't statically access them this way. – Haseeb Hassy Feb 04 '19 at 13:10
  • @HaseebHassy I edited my answer, to be more helpful. Take a look at it! – FZs Feb 04 '19 at 13:36
1

var obj = {
 "bitcoin": [
    "-0.47",
    "-0.46",
    "-0.42"
 ],
 "maker": [
    "8.29",
    "8.29",
    "6.89"
 ]
}

for (var key in obj) {
  for (var i = 0; i< obj[key].length; i++) {
    console.log(obj[key][i]);
  }
}

i don't know what you want. Tell me.

Κωλζαρ
  • 803
  • 1
  • 10
  • 22
  • I want to create an array (lets say) `bitcoin`, and add the values in it, so whenever I call that array, i can get it's values. – Haseeb Hassy Feb 04 '19 at 13:01
-2

bitcoin and maker are arrays, so items inside have no key.

const obj = {
 "bitcoin": [
    "-0.47",
    "-0.46",
    "-0.42"
 ],
 "maker": [
    "8.29",
    "8.29",
    "6.89"
 ]
}

To get the values:

var bitcoinItems = obj.bitcoin;
var firstBitcoin = bitcoinItems[0];
Héctor
  • 24,444
  • 35
  • 132
  • 243