0

i have an object with some key:value pairs. I would like to push the object into an array but without the empty object value.

my fiddle: https://jsfiddle.net/howw1fj7/

var myData = [];

var myObj = {
  product: "phone",
  quantity: 100,
  color: "red",
  secondColor: '',
  imei: "43904325"
};
myData.push(myObj); //push only not empty key:values 
$('pre').html(JSON.stringify(myData, null, 4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

i have tried something like this but this is not correct:

$.each(myObj, function(key, value) {
    if(value.length !=0) {
    var myNewObj = {key:value};
    myData.push(myNewObj);
  }
}); 
Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26
Greg Ostry
  • 1,161
  • 5
  • 27
  • 52

3 Answers3

1

You could define a utility method Object.filter as described in my answer here.

Then you get this:

Object.from = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
Object.filter = (obj, predicate) => Object.from(Object.entries(obj).filter(predicate));

var myData = [];
var myObj = { product: "phone", quantity: 100, color: "red", secondColor:'', imei: "43904325" };

myData.push(Object.filter(myObj, ([k, v]) => v !== ''));
console.log(myData);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You can use for in loop to iterate through the myObj and check for the empty value. Then you can push the new object created into the array.

var myData = [];

var myObj = { product: "phone", quantity: 100, color: "red", secondColor:'', imei: "43904325" };

var obj = {};

for(var key in myObj) {
  if(myObj[key] !== '') {
    obj[key] = myObj[key];
  }
}

myData.push(obj);

$('pre').html(JSON.stringify(myData,null,4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<pre></pre>
Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26
  • this is the solution i was looking for. in the if statement i can also check if there is something undefined or null. – Greg Ostry Aug 01 '17 at 20:54
0

value will not have a .length as it is not an array but a property in the array that you are looping over. You would need to check for null,'',undefined