1

Here I want to convert object properties to comma separated values like following- Join the elements of an array into a string:

var fruits = {"f1":"Banana", "f2":"Orange", "f3":"Apple","f4":"Mango"};
var energy = Object.keys(fruits).map(function(k){return fruits[k]}).join(",");

The result of energy will be:

Banana,Orange,Apple,Mango

But When I apply like this-

 var fruits = {"f1":"Banana", "f2":"null", "f3":"Apple","f4":"Mango"};
 var energy = Object.keys(fruits).map(function(k){return fruits[k]}).join(",");

The result of energy is like this:

Banana,,Apple,Mango

And I want result like this-

Banana,null,Apple,Mango

I have tried these links but No luck found.

Easy way to turn properties of Javascript object into comma-separated list?

Updated the Question

var fruits = {"f1":"Banana", "f2":"", "f3":"Apple","f4":"Mango"};
var energy = Object.keys(fruits).map(function(k){return fruits[k]}).join(",");

The result of energy is like this:

Banana,,Apple,Mango

I want result like this-

 Banana,null,Apple,Mango
8

3 Answers 3

6

Using Object.values would be easier.

// for "null"
var fruits = {"f1":"Banana", "f2":"null", "f3":"Apple","f4":"Mango"};
var energy = Object.values(fruits).join(",");
console.log(energy);

// for null
var fruits = {"f1":"Banana", "f2":null, "f3":"Apple","f4":"Mango"};
var energy = Object.values(fruits).map(String).join(",");
console.log(energy);

// for ""
var fruits = {"f1":"Banana", "f2":"", "f3":"Apple","f4":"Mango"};
var energy = Object.values(fruits).map(v=>v===""?"null":String(v)).join(",");
console.log(energy);

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

Comments

0
var fruits = {"f1":"Banana", "f2":"", "f3":"Apple","f4":"Mango"};
var energy = Object.keys(fruits).map(function(k){
    if(fruits [k] ==="") return "null";
    return fruits [k]        
    }).join(",");

Comments

0

about join() ,not show value null as string "null", you can check it in map() same as below :

const fruits = {"f1":"Banana", "f2":"", "f3":"Apple","f4":"Mango"};
const energy = Object.values(fruits).map(function(value){
  return !value ? "null" : value;
}).join(",");
console.log(energy);

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.