简体   繁体   中英

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

So I have an array of objects and I would like to slice the property of an object when it's empty.

For example:

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: ""
}];

I have a list of objects like that with object names randomly empty.

I would like to print to the page only the properties that are not empty.

So I'm trying to loop through the object to find the indexOf() the empty property and splice it:

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

Thanks for your help

splice is used for arrays, but when you deal with objects, you have to use delete .

You can try something like this:

 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) 

As commented by deceze , I have added handling for other cases where value can be considered as empty. Also you should check for hasOwnProperty to update properties of itself.

FYI: Using Object.keys(obj) returns an array of, unsurprisingly, an object's keys. Eg ...

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" }
**/

Using array-functions like .forEach() , .filter() , .sort() , .reduce() , and .map() etc on Objects can be really handy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM