从字典数组中获取唯一值并创建新字典

时间:2017-06-30 19:49:45

标签: javascript jquery json express dictionary

我有一个看起来像这样的JSON文件:

[{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
    "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}, {
    "name": "Cosme",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Mexican",
    "imageUrl": "/image-1.png"
}]

我正在尝试循环播放数组,识别不同的"烹饪"然后创建一个字典,其中" name"' s作为值并将匹配作为一个数组,这将成为关键。

以下是一个例子:

{ Italian: 
     [{"name": "Il Brigante",
       "rating": "5.0", etc},
      {"name": "Giardino Doro Ristorante", 
       "rating": "5.0", etc}], 
   Mexican: 
     [{"name": "Cosme", 
       "rating": "5.0", etc}]
 }

有人知道怎么做吗?任何帮助都会非常感激。非常感谢提前!!

干杯, 西奥

3 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.reduce创建生成的对象。

  

Array.prototype.reduce()

     

reduce()方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。

以下是一个例子:



var data = [{
  "name": "Il Brigante",
  "rating": "5.0",
  "match": "87",
  "cuisine": "Italian",
  "imageUrl": "/image-0.png"
}, {
  "name": "Giardino Doro Ristorante",
  "rating": "5.0",
  "match": "87",
  "cuisine": "Italian",
  "imageUrl": "/image-1.png"
}, {
  "name": "Cosme",
  "rating": "5.0",
  "match": "87",
  "cuisine": "Mexican",
  "imageUrl": "/image-1.png"
}]


var res = data.reduce(function(a, b) {
  if(a[b['cuisine']]) {
    a[b['cuisine']].push( {name: b['name'], rating: b['rating']} )
  } else {
    a[b['cuisine']] = [ {name: b['name'], rating: b['rating']} ]
  }
  return a
}, {})

console.log(res)




答案 1 :(得分:0)

我想你是为了这个。

var byCuisine = {};

myJSON.map(function (obj) {
    byCuisine[obj.cusine] = byCuisine[obj.cusine] || [];
    //can clone it with JSON.parse(JSON.stringify( )) if you want then 
     // delete newObj.cuisine to get something like your structure above.
    byCuisine[obj.cusine].push(obj);
})

答案 2 :(得分:0)

您还应该考虑使用`Array.prototype.forEach

const arr = [{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
   "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}, {
    "name": "Cosme",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Mexican",
    "imageUrl": "/image-1.png"
}];

const finalObj = {};

    arr.forEach( obj => {

       if ( ! finalObj[obj.cuisine] ) {
          let arr = [];
          arr.push(obj);
          Object.assign(finalObj, {
            [obj.cuisine]: arr
          })
       } else {
          finalObj[obj.cuisine].push(obj)
       }
  });

  console.log(finalObj);

此代码声明了一个全局const变量finalObj来保存您想要的输出。

对象的arr数组已在其他对象中循环以获取所有作为对象的元素,然后我们确定obj.cusisine上是否存在finalObj(它不在第一个实例看到一个唯一的obj.cuisine。创建一个数组来保存整个obj

的值