【问题标题】:Convert array of javascript objects to JSON将 javascript 对象数组转换为 JSON
【发布时间】:2014-04-27 03:01:52
【问题描述】:

我有一组数据格式:

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

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

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

我不知道如何做到这一点。

【问题讨论】:

  • 我建议阅读plethora of javascript tutorials 之一,以自学如何做到这一点。
  • 您目前拥有的格式更有用。不过,您应该在询问之前尝试一下。
  • 这对你有什么影响吗?请详细说明您打算如何使用新格式?

标签: javascript jquery arrays json object


【解决方案1】:

您可以使用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

【讨论】:

  • "最小化变量数量。内联变量只使用一次。利用 foreach 循环。" Spartan Programming
  • 您对此有意见吗?我看到你建议使用下划线。您意识到 underscore 的 map 函数还必须在内部创建一个变量...仅仅因为 不创建变量并不意味着您的代码更高效。此外,与加载整个库相比,为输出创建一个变量,为迭代器创建另一个变量?来吧...与此相比,这非常精简和高效。
  • @Sukima 顺便看看建议的PolyfillArray.prototype.forEach()。这只是我在这里所做的更复杂的版本......
  • 我不是在评论效率。你在小范围内是正确的。 (需要保存多少个周期?)。我在评论可读性/复杂性。都是主观的,所以要持保留态度。
  • @Sukima 我明白你在说什么。关键是为了教学的目的把事情拼出来。有时将事情分解成多个步骤会使它们更容易消化,尽管它不一定是最好看的代码。就代码的功能而言,为title 创建一个单独的变量是完全没有必要的,但确实有助于准确说明正在发生的事情。
【解决方案2】:

您要求的是将数组转换为 map ,通过特定属性键控,如果您真的想要 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"}
} 

More efficient way to search an array of javascript objects?

【讨论】:

  • 这看起来很复杂。也许 forEach 可以帮助简化它?它的工作原理只是感觉有点“有龙”-ish。 Ext 在哪里定义?
  • @Sukima Ext 是我使用的一个库,cmets 说如果你需要支持嵌套数组,你应该自己编写。你有什么难以掌握的?
【解决方案3】:

您的混合条款。我假设您询问的是使用 JavaScript 对象而不是使用 JSON 数据处理字符串。 (后者可以用JSON.parse转换)。

首先遍历数组并分配给一个对象。这种数据操作使用Underscore 效果很好,看看吧。

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

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

有点笨拙,但可以完成工作。

我个人会使用这个Underscore version

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

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2021-04-23
    • 1970-01-01
    • 2015-08-27
    • 2020-02-06
    • 2021-03-20
    • 2013-01-09
    • 2020-09-11
    相关资源
    最近更新 更多