How can I convert an object to a key-value pair array in JavaScript without using Object.entries()?
Richard W
richard w profile pic

To convert an object to a key-value pair array in JavaScript without usingObject.entries(), you can use a combination ofObject.keys() andArray.map() methods. Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13

function objectToKeyValueArray(obj) {
  return Object.keys(obj).map(function(key) {
    return [key, obj[key]];
  });
}

// Example usage
var person = { name: 'John', age: 30, city: 'New York' };
var keyValueArray = objectToKeyValueArray(person);

console.log(keyValueArray);
// Output: [ ['name', 'John'], ['age', 30], ['city', 'New York'] ]

In the above code, theobjectToKeyValueArray() function takes an object as an argument. It usesObject.keys(obj) to retrieve an array of the object's keys. Then,Array.map() is used to iterate over the keys array and create a new array where each element is an array containing the key-value pair. Finally, the resulting array is returned. By callingobjectToKeyValueArray(person), whereperson is an example object, you'll get the desired key-value pair array. Each element of the array is itself an array with two elements, representing the key and its corresponding value from the original object. It's important to note that this approach creates a shallow copy of the object, meaning that if the object contains nested objects or arrays as values, those nested references will be retained in the resulting key-value pair array. If you need a deep copy, you would need to modify the code accordingly.