7

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?

PS: I get the right result! Just wanted to know if it is the elengant way or not?

5
  • 1
    If those objects have more than one property, there's no guarantee which one you'll get as property 0. Commented Jun 29, 2015 at 19:17
  • They always have one property; I hate fromObj[c][Object.keys(fromObj[c])[0]] though! Commented Jun 29, 2015 at 19:18
  • 2
    Save the result of calling Object.keys(fromObj[c])[0] instead of calling that multiple times. Just add another var. Commented Jun 29, 2015 at 19:19
  • these kind of questions should be posted there codereview.stackexchange.com Commented Jun 29, 2015 at 19:22
  • 1
    @Pasargad Both approaches are good and I don't see any preference... Commented Jun 30, 2015 at 13:53

1 Answer 1

10

It can be simpler with 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 ));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.