1

I have an object, from which an array has to be made, where key + value pairs are converted to strings.

var obj = {'x': 1, 'y': 2, 'z':3};

I have tried to convert the content to strings:

var joined = Object.entries(obj ).join(' ');

"x,1 y,2 z,3"

and to an array of arrays

var entries = Object.entries(obj);

But it is not exactly what I need

My ideal result is

var arrayFromObject = ['x 1', 'y 2', 'z 3'];

I can probably flatten the array of arrays but maybe there is a better solution?

5 Answers 5

4

You can get the desired output using .map(), .join() and Object.entries():

  • Get an array of [key, value] pairs of a given object's properties using Object.entries().
  • Iterate using .map() over the array values returned in first step and use .join() to get the string in desired format.

const obj = {'x': 1, 'y': 2, 'z': 3};

const array = Object.entries(obj).map(a => a.join(' '));

console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

1

If you know you have a KVP set, you can do something like

const obj = {'x': 1, 'y': 2, 'z':3};
const result = Object.entries(obj).map(entry => `${entry[0]} ${entry[1]}`);
//(3) ["x 1", "y 2", "z 3"]

Comments

1
Object.keys(obj).map(x => `${x} ${obj[x]}`)

Explanation

Object.keys(obj) returns ["x", "y", "z"] and map then maps every key to a template literal ${x} ${obj[x]} where obj[x] is the value (y is mapped to y 2)

Comments

0

You can use for loop for your desired output, you could've used map but it creates performance issues if the list is large.

let obj = { x: 1, y: 2, z: 3 };
let outputArray = [];
for (let i = 0; i < Object.keys(obj).length; i++) {
  outputArray.push(Object.keys(obj)[i]+' '+Object.values(obj)[i]);
}

console.log(outputArray);

Comments

0

const obj = {'x': 1, 'y': 2, 'z':3};

const array = Object.entries(obj).map(a => a.join(' '));

console.log(array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.