如何在Lodash中将数组转换为对象?

时间:2016-07-22 13:55:07

标签: javascript lodash

我有:

{
     dis:{["String1","String2","String3"]},
     par:"pony"
}

我想把它变成这个:

[
    { name: 'String1', value: "pony" },
    { name: 'String2', value: "pony" },
    { name: 'String3', value: "pony" }
]

3 个答案:

答案 0 :(得分:2)

如果您更改为有效的js数据,则可以使用reduce()

执行此操作

var obj = {
  dis: ["String1", "String2", "String3"],
  par: "pony"
}

var result = obj.dis.reduce(function(r, e) {
  r.push({name: e, value: obj.par});
  return r;
}, []);

console.log(result)

答案 1 :(得分:0)

你可以轻松完成,但要注意你有双括号(胡须和方括号)。

var 
    data = {
        dis: ["String1","String2","String3"],
        par: "pony"
    }, 

  result = [];

for (var index in data.dis)
    result.push({ name: data.dis[index], value: data.par}

你可以找到小提琴here

答案 2 :(得分:0)

您可以使用Array.protoype.map执行此操作:

var obj = {
     dis:["String1","String2","String3"],
     par:"pony"
};

var arrOfObj = obj.dis.map(function(name) {
    return {
        name: name,
        value: obj.par
    }
});

console.log(arrOfObj)

或者lodash的_.map

var obj = {
     dis:["String1","String2","String3"],
     par:"pony"
};

var arrOfObj = _.map(obj.dis, function(name) {
    return {
        name: name,
        value: obj.par
    }
});

console.log(arrOfObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>