Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - How to break up an object with a string of values to create a new array of objects?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...