Uncertain about the statement "I get all the values, so I tried it with Object.values(fruits.apple) to specify the key," because in your code, you're actually retrieving all the values from the entire array instead of just apple. Also, note that the property apple itself does not possess multiple "values", but rather a single value.
Object.values is a function designed to accept an object as input and output an array containing only the values present within the object, typically arranged alphabetically based on keys. However, the final result has no direct link back to the original keys or object structure, making it impossible to determine which values correspond to which keys.
Therefore, it's somewhat challenging to decipher your objective. If you aim to solely add the value of "apple" to an empty array, consider using emptyArray.push(fruits.apple)
. Alternatively, if you intend to create a method for appending the value of any fruit to an array, utilize bracket notation within a function like so:
const fruity = (arr, obj, key) => arr.push(obj[key])
, then call it with your variables:
fruity(emptyArray, fruits, "apple")
If your goal involves transforming both keys and values into a new array format that allows for further manipulation, consider employing Object.entries
. This function transforms an object into a two-dimensional array where each sub-array contains the key-value pair from the original object.
To use it, simply invoke
var newArray = Object.entries(fruits)
. This approach proves useful when incorporating transformations via methods such as Array.map or Array.forEach. However, for basic operations like adding an object property to an array, refer back to the previous paragraphs for guidance.