如何用一串值分解一个对象以创建一个新的对象数组? [英] How to break up an object with a string of values to create a new array of objects?
问题描述
我正在研究 提出了另一个问题,我想出了一个解决方案,但我相信有一种更优雅的方法来做到这一点.假设您有一个对象,其中所有值都是以逗号分隔的值字符串,如下所示:
{ "action" : "goto,goto", "target" : "http://www.google.com,http://www.cnn.com" }
但是,您希望将值分开并将对象分解为对象数组,如下所示:
<预><代码>[{ "action" : "goto", "target" : "http://www.google.com" },{ "action" : "goto", "target" : "http://www.cnn.com" }]这是我的解决方案:
var actions = obj.action.split(',');var 目标 = obj.target.split(',');//组合动作和目标数组var combineData = _.zip(actions, targets);//遍历组合数据数组并使用正确的键创建一个对象var commandList = _.map(combinedData, function(value) {return _.object(["action", "target"], value)});
这符合我的要求并且看起来并不可怕,但是有没有更巧妙的方法来实现这一点?
功能风格很棒.这是一种更直接的方法.
var newObjects = [];for(var k in o) {var vals = o[k].split(',');for(var i = 0, len = vals.length; i < len; i++) {newObjects[i] = newObjects[i] ||{};newObjects[i][k] = vals[i];}}
在你为这个操作想出一个漂亮的、紧凑的、语义化的名称之前,我不会太担心实现.有什么想法吗?
I was working on a solution to another question posed, and I came up with a solution, but I'm convinced that there's a more elegant way to do it. Let's say that you have an object where all of the values are a string of values separate by commas, like this:
{ "action" : "goto,goto", "target" : "http://www.google.com,http://www.cnn.com" }
But, you'd like to separate the values and break up the object into an array of objects, like this:
[
{ "action" : "goto", "target" : "http://www.google.com" },
{ "action" : "goto", "target" : "http://www.cnn.com" }
]
Here's what my solution was:
var actions = obj.action.split(',');
var targets = obj.target.split(',');
// combined the actions and targets arrays
var combinedData = _.zip(actions, targets);
// go through the combinedData array and create an object with the correct keys
var commandList = _.map(combinedData, function(value) {
return _.object(["action", "target"], value)
});
This does what I want and doesn't look terrible, but is there a slicker way of accomplishing this?
Functional style is great. Here's a more direct approach.
var newObjects = [];
for(var k in o) {
var vals = o[k].split(',');
for(var i = 0, len = vals.length; i < len; i++) {
newObjects[i] = newObjects[i] || {};
newObjects[i][k] = vals[i];
}
}
I wouldn't worry too much about the implementation until you come up with a nice, compact, semantic name for this operation. Any ideas?
这篇关于如何用一串值分解一个对象以创建一个新的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!