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

How to splice an empty property of an object that's into an array?

所以我有一个对象数组,我想在一个对象的 属性 为空时对其进行切片。

例如:

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

感谢您的帮助

拼接用于数组,但是当你处理对象时,你必须使用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 以更新其自身的属性。

仅供参考:毫无疑问,使用 Object.keys(obj) returns 对象键数组。例如。 ...

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() 等数组函数非常方便。