简体   繁体   中英

Removing specific key-value pairs from a document/object

I have a document that looks like something like this:

{
  name: "Johnny Boy",
  age: 24,
  hobbies: ["fencing", "chess", "raves"],
  _createdAt: 2015-05-15T18:12:26.731Z,
  _createdBy: "JohnnyBoy",
  _id: mQW4G5yEfZtsB6pcN
}

My goal is to return everything that doesn't start with an underscore , and format it a bit differently so I will end up with this:

[
  {
    fieldName: "name",
    value: "Johnny Boy"
  },
  {
    fieldName: "age",
    value: 24
  },
  {
    fieldName: "hobbies",
    value: ["fencing", "chess", "raves"]
  }
]

My initial solution was to run it through the _.map function of the Underscore library (which has nothing to do with my wanting to remove underscores specifically...) and then using lastIndexOf to figure out which keys begin with an underscore:

var listWithoutUnderscores = _.map(myList, function(val, key) {
  if (key.lastIndexOf("_", 0) === -1)
    return {fieldName: key, value: val}
  return null
})

However, this will literally return null instead of the fields that began with _ in the returned array:

[
  ...
  {
    fieldname: "hobbies",
    value: ["fencing", "chess", "raves"]
  },
  null,
  null,
  null
]

I want to remove them completely , ideally within the map function itself, or else by chaining it through some kind of filter but I don't know which one is fastest in this case.

Underscore also comes with an array method compact which will remove all falsey and null values from an array:

_.compact([0, 1, false, 2, '', null, 3]);
=> [1, 2, 3]

You could just call _.compact(array) on the array after your map.

You can use reduce for this:

var listWithoutUnderscores = _.reduce(myList, function(list, val, key) {
  if (key.lastIndexOf("_", 0) === -1){
    list.push( {fieldName: key, value: val});
  }
  return list;
}, []);

You can use pick and pass a predicate to get the valid keys and then map across those fields:

var validKey = function(value, key){
    return _.first(key) != '_';
}

var createField = function(value, key){
    return {
        fieldname: key,
        value: value
    }
}

var result = _.chain(data)
    .pick(validKey)
    .map(createField)
    .value();

 var data = { name: "Johnny Boy", age: 24, hobbies: ["fencing", "chess", "raves"], _createdAt: '2015-05-15T18:12:26.731Z', _createdBy: "JohnnyBoy", _id: 'mQW4G5yEfZtsB6pcN' } var validKey = function(value, key){ return _.first(key) != '_'; } var createField = function(value, key){ return { fieldname: key, value: value } } var result = _.chain(data) .pick(validKey) .map(createField) .value(); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

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