如何使用jquery将非空键值对象推入数组

时间:2017-08-01 20:40:31

标签: javascript jquery

我有一个带有一些键的对象:值对。我想将对象推入数组但没有空对象值。

我的小提琴: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>

我尝试过这样的事情,但这不正确:

$.each(myObj, function(key, value) {
    if(value.length !=0) {
    var myNewObj = {key:value};
    myData.push(myNewObj);
  }
}); 

3 个答案:

答案 0 :(得分:1)

您可以按照in my answer here所述定义实用工具方法Object.filter

然后你明白了:

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

答案 1 :(得分:0)

您可以使用for in循环遍历myObj并检查空值。然后,您可以将创建的新对象推送到数组中。

&#13;
&#13;
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));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<pre></pre>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

value不会有.length,因为它不是数组,而是数组中要循环的属性。您需要检查null''undefined