0

const dataParams = [];  
let data={
         A:'5',
         B:'6',
         C:'7',
         D:'8'
       }
for(let d in data){
 dataParams.push(d + '=' + data[d]);  
}
console.log(dataParams)

I have an object as below i just need to print it as an array like ["A=5", "B=6", "C=7", "D=8"]

The Below code is working please see the console.

But i have read about the keys and values method in JS

Object.keys(data) // [A,B,C,D] Object.values(data) // ['5','6','7','8']

Is there any way that i can get the same output with the help of using keys and values method

3 Answers 3

1

Use object#entries with array#map

let data={A:'5',B:'6',C:'7', D:'8'},
  result = Object.entries(data).map(([key, value]) => `${key}=${value}`);
  console.log(result);

You can also use Object.keys()

let data={A:'5',B:'6',C:'7', D:'8'},
      result = Object.keys(data).map(k => `${k}=${data[k]}`);
      console.log(result);

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

1 Comment

Thank for the quick response !!:)
0

You can use reduce with Object.keys

var data = {
  a:1,
  b:2,
  c:3,
  d:4
}

var list = Object.keys(data).reduce(function(keyValueList, prop){
  keyValueList.push(prop + '=' + data[prop])
  return keyValueList;
}, []);

console.log(list);

Comments

0

As you're using both key and value, Object.entries is probably best for you:

const dataParams = Object.entries(data).map(([key, value]) => `${key}=${value}`);

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.