检查对象中哪个属性保存值的最快方法?

时间:2016-09-19 08:47:45

标签: javascript object

可能是一个愚蠢的问题,假设我有一个像下面这样的对象,

{"Country":"country","Continent":"continent","Province":"","District":"","State":"state","City":""}"

在不使用循环的情况下,检查哪些属性保存上述对象中的值的最快方法是什么?

在for循环中执行此操作时,

if(typeof someUndefVar == whatever) -- works

预期输出

国家,大陆和州

4 个答案:

答案 0 :(得分:5)

var a = {"Country":"country","Continent":"continent","Province":"","District":"","State":"state","City":""};

Object.keys(a).filter( prop => a[prop] );

这还取决于您希望如何处理0nullundefined值。

答案 1 :(得分:1)

您可以执行以下操作;

var obj  = {"Country":"country","Continent":"continent","Province":"","District":"","State":"state","City":""};
for (var prop in obj) !!obj[prop] && console.log(prop);

答案 2 :(得分:0)

您需要使用object.keys()功能

像这样,

var jsonData= {"Country":"country","Continent":"continent","Province":"","District":"","State":"state","City":""};
console.log(Object.keys(jsonData));

希望这有帮助!

答案 3 :(得分:0)

对不起,你说没有循环,我很兴奋,我很无聊,我有功能。

首先,我缩短了一些名字,我猜他们有点自我解释:

  • head:数组的第一个元素
  • tail:所有元素,但第一个
  • isEmpty:检查数组是否长度为0

transform使用回调执行实际工作,如果keys数组为空则如果不递归则停止。

var data = {"Country":"country","Continent":"continent","Province":"","District":"","State":"state","City":""}

// plumbing
var head = (a) => a[0]
var tail = (a) => a.slice(1)
var isEmpty = (a) => a.length === 0

// actual stuff happens here
var transform = (obj, callback) => {

    var withval = (keys) => {

      if(isEmpty(keys)) return

      var p = head(keys)

      if(!!obj[p]) callback(p)

      withval(tail(keys))
    }

    withval(Object.keys(obj))
}

// Logs
var log = (p) => console.log(p)
transform(data, log)

// Array making
var arr = [];
var toArr = (p) => arr.push(p)
transform(data, toArr)
console.log(arr)

// Object making
var obj = {}
var toObj = (p) => obj[p] = data[p]
transform(data, toObj)
console.log(obj)

结果:

Country
Continent
State
[ 'Country', 'Continent', 'State' ]
{ Country: 'country', Continent: 'continent', State: 'state' }