繁体   English   中英

将javascript对象数组转换为JSON

[英]Convert array of javascript objects to JSON

我有一组格式的数据:

[{"title":movietitle1, "id":445, "release":"16JUN1985"}, {"title":movietitle2, "id":487, "release":"12AUG1993"}]

我需要转换为JSON格式如下:

{ "movietitle1":{"id":445,"release":"16JUN1985"}, "movietitle2":{"id":487, "release":"12AUG1993"} }

我不知道如何实现这一目标。

您可以使用JSON.stringify()和一些基本数据操作来完成此操作。

将数据存储在变量中,我们将其称为input_data

循环遍历您的数据并使用每个条目构建另一个变量,我们称之为output_data

// create an object to store the newly formatted data
var output_data = {};
// the code in here is run once for each item in input_data
for (var i = 0; i < input_data.length; i++) {
  // get the current item's title
  var title = input_data[i].title;
  // use the title as the key in the output data
  //  and assign the other values to that key
  output_data[title] = {
    id: input_data[i].id,
    release: input_data[i].release
  };
} 

// use JSON.stringify() to make a valid JSON string
var json = JSON.stringify(output_data);

// now use the variable json which contains your JSON string

你的混音条款。 我假设您要求使用JavaScript对象操作数据而不是使用JSON数据操作字符串。 (后者可以使用JSON.parse转换)。

首先遍历数组并分配给对象。 使用Underscore ,这种数据操作很有效,请查看。

在vanilla JS中,让我们尝试这样的事情:

var newData = {};
data.forEach(function(item) {
  var title = item.title;
  delete item.title;
  newData[title] = item;
});

有点狡猾,但完成工作。

就个人而言,我会使用这个Underscore版本

var newData = _(data).chain()
  .map(function(item) {
    return [item.title, _(item).omit('title')];
  })
  .object()
  .value();

您要求的是将数组转换为地图,按特定属性键入,如果您真的想要JSON,则可以在生成的JS对象上调用JSON.stringify。

http://jsfiddle.net/FfE8f/1/

/**
 * Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
 * This method supports nested lists
 * Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
 * Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
 * @param {object[]} list of objects to be transformed into a keyed object
 * @param {string} keyByProp The name of the property to key by
 * @return {object} Map keyed by the given property's values
 */
function mapFromArray (list , keyByProp) {
  var map = {};
  for (var i=0, item; item = list[i]; i++) {
    if (item instanceof Array) {
      // Ext.apply just copies all properties from one object to another,
      // you'll have to use something else. this is only required to support nested arrays.
      Ext.apply(map, mapFromArray(item, keyByProp));
    } else {
      map[item[keyByProp]] = item;
    }
  }
  return map;
};

console.log(mapFromArray([
    {"title": "title 1", "id":445, "release":"16JUN1985"}, 
    {"title":"movietitle2", "id":487, "release":"12AUG1993"}],
    "title"
)));
// outputs
{
    "title 1": {"title":"title 1","id":445,"release":"16JUN1985"},
    "movietitle2": {"title":"movietitle2","id":487,"release":"12AUG1993"}
} 

查看更有效的方法来搜索javascript对象数组?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM