简体   繁体   English

减少Javascript

[英]Reduce in Javascript

So I want to convert: 所以我想转换:

From : 来自

{
  emailNotify: {
    EQ: true
  },
  foo: {
    bar: false
  }
}

To :

[
  {'condition': 'EQ', 'attribute': emailNotify, 'value': true},
  {'condition': 'bar', 'attribute': foo, 'value': false}
]

I tried the following code: 我尝试了以下代码:

var fromObj={
   emailNotify: {
        EQ: true
    },
    foo: {
        bar: false
    }
};

console.log(Object.keys(fromObj));
var result = (Object.keys(fromObj)).reduce(function(p,c,i,a){
    var newObj={};
    newObj["condition"]=Object.keys(fromObj[c])[0];
    newObj["attribute"]=c;
    newObj["value"]=fromObj[c][Object.keys(fromObj[c])[0]];
    p.push(newObj);
    return p;
},[]);


console.log("result", result);

Is this the way you to would do it as well? 这是你这样做的方式吗? I believe I'm not using reduce correctly? 我相信我没有正确使用Redu?

PS: I get the right result! PS:我得到了正确的结果! Just wanted to know if it is the elengant way or not? 只是想知道它是否是一种强势方式?

It can be simpler with Array.prototype.map : 使用Array.prototype.map可以更简单:

 var fromObj={ emailNotify: { EQ: true }, foo: { bar: false } }; var result = Object.keys(fromObj).map(function(key) { var subObj = Object.keys(fromObj[key]); return { condition: subObj[0], attribute: key, value: fromObj[key][subObj[0]] }; }); alert(JSON.stringify( result, null, 4 )); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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