Javascript:将两个数组合并为单个对象,而不会丢失键顺序

时间:2016-06-08 09:28:33

标签: javascript arrays mapreduce reduce

我有两个字符串中的原始imdb数据:

var headers = "ID   imdbID  Title   Year    Rating  Runtime Genre   Released    Director    Writer  Cast    Metacritic  imdbRating  imdbVotes   Poster  Plot    FullPlot    Language    Country Awards  lastUpdated";


const content = "1  tt0000001   Carmencita  1894    NOT RATED   1 min   Documentary, Short      William K.L. Dickson        Carmencita      5.8 1136    http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng@@._V1_SX300.jpg    Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face.           USA     2016-05-04 00:03:31.600000000";

当然我正在清理标签和空格等,并创建两个这样的数组:

const values = content.split(/(\t+)/).filter( (part) => !/\t/.test(part) );

let keys = headers.split(/(\s+)/).filter( (part) => !/\s+/.test(part) );

现在我想将keys数组中的键映射到values数组中的值。所以我做了这样的减少:

var result = {};

values.reduce( (acc, val, index) => {
  return result[ keys[index] ] = val; 
}, result);

这给了我一个最终的result对象,如下所示:

 {
  Cast: "1136",
  Director: "Carmencita",
  Genre: "Documentary, Short",
  ID: "1",
  imdbID: "tt0000001",
  imdbRating: "Performing on what looks like a small wooden stage, wearing a dress with a hoop skirt and white high-heeled pumps, Carmencita does a dance with kicks and twirls, a smile always on her face.",
  imdbVotes: "USA",
  Metacritic: "http://ia.media-imdb.com/images/M/MV5BMjAzNDEwMzk3OV5BMl5BanBnXkFtZTcwOTk4OTM5Ng@@._V1_SX300.jpg",
  Poster: "2016-05-04 00:03:31.600000000",
  Rating: "NOT RATED",
  Released: "William K.L. Dickson",
  Runtime: "1 min",
  Title: "Carmencita",
  Writer: "5.8",
  Year: "1894"
}

如您所见,订单全部混乱!如何在数据中获得正确的顺序,以便将title键映射到电影标题值等?

我愿意使用像lodash之类的库来实现这一目标,但不知道我应该使用什么?这是一个当前状态的jsbin演示:https://jsbin.com/gekawi/edit?js,console

1 个答案:

答案 0 :(得分:2)

如果您使用里面的标签获取原始数据,您可以使用它们进行拆分。

String selection = "id IN ( ?,?,? ) && status IN (? ,? ,? )";
String[] selectionArgs = new String[]{"1","2",null,"A","B",null};