如何将对象的空属性拼接成数组?

时间:2016-09-01 12:56:36

标签: javascript arrays object splice

所以我有一个对象数组,我希望在对象空的时候对其进行切片。

例如:

var quotes = [
{
    quote: "Bolshevism is not a policy; it is a disease. It is not a creed; it is a pestilence.",
    source: "Winston Churchill",
    citation: "",
    year: "29 May 1919",
    place: ""
},
{
    quote: "Learn while you live",
    source: "",
    citation: "X",
    year: "1950",
    place: ""
}];

我有一个对象列表,对象名称随机为空。

我想在页面上只打印非空的属性。

所以我试图遍历对象以找到indexOf()空属性并拼接它:

function findEmptyProp(quotes) {
   for (prop in quotes) {
     if(quotes[i].children === '') {
        return indexOf(quotes[i]);
        quotes.splice(i, 1);
}}}

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

splice用于数组,但是当你处理对象时,你必须使用delete

您可以尝试这样的事情:



var quotes = [{
  quote: "Bolshevism is not a policy; it is a disease. It is not a creed; it is a pestilence.",
  source: "Wyston Churchill",
  citation: "",
  year: "29 May 1919",
  place: ""
}, {
  quote: "Learn while you live",
  source: "",
  citation: "X",
  year: "1950",
  place: ""
}];

quotes.forEach(function(o){
  for (var k in o){
    if(o.hasOwnProperty(k) && isEmpty(o[k])){
      delete o[k];
    }
  }
});

function isEmpty(val){
  return val === undefined || 
    val === null || 
    (typeof(val) === "object" && Object.keys(val).length === 0) || 
    (typeof(val) === "string" && val.trim().length === 0)
}

console.log(quotes)




正如deceze所评论的那样,我已经为其他可以认为值为空的情况添加了处理。另外,您应该检查hasOwnProperty以更新自身的属性。

答案 1 :(得分:2)

仅供参考:使用Object.keys(obj)返回一个对象密钥的数组,不出所料。例如。 ...

var arrayOfObjects = [
  {
    prop1: '1',
    prop2: '2',
    prop3: ''
  },
  {
    prop1: '1',
    prop2: '',
    prop3: '3'
  },
  {
    prop1: '',
    prop2: '2',
    prop3: '3'
  }
];

arrayOfObjects.forEach(function(obj) {
    /* 'obj' = each object in 'arrayOfObjects' */
    Object.keys(obj).forEach(function(key) {
        /* 'key' = each key in 'obj' */
        if (obj[key] === '') delete obj[key];
    });
});

/* test arrayOfObjects */
arrayOfObjects.forEach(function(obj) {
    console.debug(obj);
});

/** =>
    Object { prop1: "1", prop2: "2" }
    Object { prop1: "1", prop3: "3" }
    Object { prop2: "2", prop3: "3" }
**/

在对象上使用.forEach().filter().sort().reduce().map()等数组函数非常方便。