-3

I'm using Ant Design framework for my react project. I want to get access to the inner object "quote.USD.price" and put it on the dataSource array but unfortunately, I don't know how. inner object value access

mld
  • 25
  • 5

2 Answers2

2

From what I understand you are looking for something like this. You can access inner fields of objects in any of the below methods

const crypto = {
  quote: {
    USD: {
      price: 10
    }
  }

}

const data1 = {
  title: "price",
  dataIndex: crypto.quote.USD.price,
  key: "id"
}

const data2 = {
  title: "price",
  dataIndex: crypto["quote"]["USD"]["price"],
  key: "id"
}


console.log(data1)
console.log(data2)
//both should output the same
cmgchess
  • 7,996
  • 37
  • 44
  • 62
  • Perfect. Thank you Yeah I just saw in their documentation "Besides, the breaking change is changing dataIndex from nest string path like user.age to string array path like ['user', 'age']" – mld Oct 23 '21 at 17:37
0

I think you want to parse a string that is concatenated with dots that represents the location of a value inside some nested objects.

I wrote a utility function to recursively does that. You can see it in action in this React project. I did it with TypeScript but you can remove the type annotations.

const findPriceByMultipleKeys = (dataKey: string, data: any): string | number => {
  let keys: string[] = dataKey.split(".");
  // If dataKey is one key without any dot notation, return the value
  if(keys.length === 1) return data[dataKey];

  let key: string = "";
  let keysRest: string[] = [];

  if (keys.length) {
    // get first element from keys
    // capture the rest of the keys
    [key, ...keysRest] = keys;
  }
  // Check if there any more indexes left to evaluate
  if (keysRest.length) {
    // Transform keysRest to string concatenated with dots
    let keysRestStr = keysRest.join(".");
    // Let the function call itself to go deeper in the object with
    // the remaining indexes and objects
    return findPriceByMultipleKeys(keysRestStr, data[key]);
  } else {
    // If no keys left to evaluate, return the value
    return data[key];
  }
};

zimmerbimmer
  • 908
  • 7
  • 24