'How do you get an array of object.key(not values, not string, not only keys) from an object?

I have this object

let listItem = {
  name: "Lydia",
  accountId: "HGVe",
  fleetType: "Haulage"
};

I want to get an array which will be exactly like this:

[listItem.name, listItem.accountId, listItem.fleetType]

The values in the array don't have to be strings or values as you can see.

So every element of the array is going to be VariableName.key (not a string).

!!!!To be 100% clear, these 2 results are NOT what I need:

["listItem.name", "listItem.accountId", "listItem.fleetType"] // results are strings: WRONG
["Lydia", "HGVe", "Haulage"] // results are values: WRONG

As you can see above, the correct array have in each element a reference to the precise object.key



Solution 1:[1]

Based on your edit, you want to store object references of listItem object's properties.

let listItem = {
  name: "Lydia",
  accountId: "HGVe",
  fleetType: "Haulage"
};

But this object's properties are not objects but primitive values. Primitive values don't have a reference. See this answer for more information.

You can create a string object using String constructor. And use Object.values() to get these values.

let listItem = {
  name: new String("Lydia"),
  accountId: new String("HGVe"),
  fleetType: new String("Haulage")
};

let refs = Object.values(listItem);

console.log(refs);

You now have references stored in an array. You can't have [listItem.name, listItem.accountId, listItem.fleetType] without them getting evaluated to those references.


Previous Answer:

You can wrap this object in another object and use Object.keys() to get its name.

Then use Object.keys() on original object to get its keys.

let listItem = {
  name: "Lydia",
  accountId: "HGVe",
  fleetType: "Haulage"
};

var obj = { listItem };
var name = Object.keys(obj)[0];
var result = [];

Object.keys(listItem).forEach((key) => {
  result.push(name + "." + key);
});

console.log(result);

So every element of the array is going to be VariableName.key (not a string).

Every value should have a data type. So what would be the data type of these values? They are likely to be strings.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1