我正在尝试从服务器解析json响应.对于服务器端,我无能为力,因为无法在任何时候更改它.
他们的json响应如下所示:
{
prop[1][foo]: "foo number 1",
prop[1][bar]: "bar number 1",
prop[1][bazz]: "bazz number 1",
prop[2][foo]: "foo number 2",
prop[2][bar]: "bar number 2",
prop[2][bazz]: "bazz number 2"
}
现在我希望它像这样:
{
props: [
{foo: "foo number 1", bar: "bar number 1", bazz: "bazz number 1"},
{foo: "foo number 2", bar: "bar number 2", bazz: "bazz number 2"}
]
}
我该怎么做,我不知道如何迭代和设置.
我的尝试:
var temp = [];
var regExp = /\[([^)])\]/;
var matches;
_.each(element, function(value, key) {
if (key.indexOf('foo') >= 0) {
matches = regExp.exec(key);
temp[matches[1]] = value;
}
});
解决方法:
您可以使用_.set(object, path, value)
,它将评估为响应对象中的每个值设置的路径.
Java脚本
var data = {
"prop[1][foo]": "foo number 1",
"prop[1][bar]": "bar number 1",
"prop[1][bazz]": "bazz number 1",
"prop[2][foo]": "foo number 2",
"prop[2][bar]": "bar number 2",
"prop[2][bazz]": "bazz number 2"
};
function evaluate(data) {
var newData = {};
_.each(data, function(value, key) {
_.set(newData, key, value);
});
return definedItemsOnly(newData);
}
// Since the resulting value of the given data set above
// doesn't have prop[0] then this function below
// will provide you the means of removing any potential
// undefined values in an array or possibly undefined
// key values in an object.
function definedItemsOnly(item) {
var isDefined = _.negate(_.isUndefined);
if(_.isArray(item)) {
return _.filter(item, isDefined);
} else if(_.isObject(item)) {
return _(item).pick(isDefined).mapValues(definedItemsOnly).value();
}
return item;
}
console.log(evaluate(data));
如果您希望_.each回调以更加组合的形式,则可以像下面这样更改validate()函数:
function evaluate(data) {
var newData = {};
_.each(data, _.rearg(_.partial(_.set, newData), [1, 0]));
return definedItemsOnly(newData);
}