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);
  }
}); 
3
  • What is your definition of empty? A '' string? Zero? null? undefined? NaN? Commented Aug 1, 2017 at 20:43
  • If you want to name a property dynamically in an object literal, the syntax should be: { [key]: value }. Of course the interpreter should support es6. Commented Aug 1, 2017 at 20:45
  • in this case empty definition is A ' ' Commented Aug 1, 2017 at 20:49

3 Answers 3

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);

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

Comments

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>

1 Comment

this is the solution i was looking for. in the if statement i can also check if there is something undefined or null.
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

2 Comments

disagree , if the value is a string then it will have the length property
true. but then you are only looking at strings

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.