首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果存在键,则使用键和值形成JSON

如果存在键,则使用键和值形成JSON
EN

Stack Overflow用户
提问于 2018-09-21 13:05:44
回答 4查看 613关注 0票数 0

我有一个JSON结构,类似于:

代码语言:javascript
复制
    [  
   {  
      "name":"angelinas"
   },
   {  
      "name":"besuto"
   },
   {  
      "name":"catch",
      "cuisine":"Japanese"
   },
   {  
      "name":"center cut"
   },
   {  
      "name":"fedora"
   },
   {  
      "name":"Habanero",
      "cuisine":"Mexican"
   },
   {  
      "name":"Indies"
   },
   {  
      "name":"new"
   },
   {  
      "name":"RazINN"
   },
   {  
      "name":"restaurantTestVenue779"
   },
   {  
      "name":"restaurantTestVenue9703"
   },
   {  
      "name":"Salsa ",
      "cuisine":"Mexican"
   },
   {  
      "name":"Sushi Place",
      "cuisine":"Japanese"
   },
   {  
      "name":"The Ashoka"
   },
   {  
      "name":"The Poboys"
   },
   {  
      "name":"the shogun"
   },
   {  
      "name":"vinyard view"
   }
]

使用上面的JSON,我想确定一种菜肴是否与餐馆联系在一起。如果是,我想构建一个JSON结构,类似于:

代码语言:javascript
复制
[  
   {  
      "Mexican":{  
         "venueNames":[  
            "Habanero",
            "Salsa"
         ]
      }
   },
   {  
      "Japanese":{  
         "venueNames":[  
            "Sushi Place",
            "catch"
         ]
      }
   }
]

已经尝试使用for循环和.hasProperty构建JSON,但没有成功。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-09-21 14:02:25

您可以在下面的一个循环中使用。

代码语言:javascript
复制
data.forEach(function(item) {
    // if item has cuisine and cuisine not exist in new array
    if(item["cuisine"] != null && typeof newArr.find(v => v[item.cuisine] != null) == 'undefined') {
    // create new object with structure
    let obj = {};
    obj[item.cuisine] = {
         "venueNames":[item.name]
      };

    newArr.push(obj);
  }
  else {
    // else find existing cuisine and add new venue
    let obj = newArr.find(v => v.hasOwnProperty(item.cuisine));
    if(typeof obj != 'undefined') {
        obj[item.cuisine].venueNames.push(item.name);
    }
  }
});

JSFIDDLE

票数 0
EN

Stack Overflow用户

发布于 2018-09-21 13:24:42

这就是你能做的!首先遍历数据,并使用"hasOwnProperty“方法来检查菜系是否存在,以及它是否存在,然后检查您的菜系对象是否有该菜系,然后再将其添加到其中。

代码语言:javascript
复制
const data = [{
        "name": "angelinas"
    },
    {
        "name": "besuto"
    },
    {
        "name": "catch",
        "cuisine": "Japanese"
    },
    {
        "name": "center cut"
    },
    {
        "name": "fedora"
    },
    {
        "name": "Habanero",
        "cuisine": "Mexican"
    },
    {
        "name": "Indies"
    },
    {
        "name": "new"
    },
    {
        "name": "RazINN"
    },
    {
        "name": "restaurantTestVenue779"
    },
    {
        "name": "restaurantTestVenue9703"
    },
    {
        "name": "Salsa ",
        "cuisine": "Mexican"
    },
    {
        "name": "Sushi Place",
        "cuisine": "Japanese"
    },
    {
        "name": "The Ashoka"
    },
    {
        "name": "The Poboys"
    },
    {
        "name": "the shogun"
    },
    {
        "name": "vinyard view"
    }
]

let cuisines = {};


for (const resturant of data) {
    if (resturant.hasOwnProperty('cuisine')) {

        if (cuisines.hasOwnProperty(resturant.cuisine)) {
            cuisines[resturant.cuisine].venueNames.push(resturant.name);
        } else {
            cuisines[resturant.cuisine] = {
                venueNames: [resturant.name]
            };
        }
    }
}
票数 1
EN

Stack Overflow用户

发布于 2018-09-21 13:38:08

这是数组的一个简单的缩减。如果餐厅有明确的菜肴,检查结果是否已经定义了这种菜肴。如果不是,为它创建一个对象,您可以在其中推送餐厅名称。

代码语言:javascript
复制
const restaurants = [
   {  
    "name":"angelinas"
   },
   {  
    "name":"besuto"
   },
   {  
    "name":"catch",
    "cuisine":"Japanese"
   },
   {  
    "name":"center cut"
   },
   {  
    "name":"fedora"
   },
   {  
    "name":"Habanero",
    "cuisine":"Mexican"
   },
   {  
    "name":"Indies"
   },
   {  
    "name":"new"
   },
   {  
    "name":"RazINN"
   },
   {  
    "name":"restaurantTestVenue779"
   },
   {  
    "name":"restaurantTestVenue9703"
   },
   {  
    "name":"Salsa ",
    "cuisine":"Mexican"
   },
   {  
    "name":"Sushi Place",
    "cuisine":"Japanese"
   },
   {  
    "name":"The Ashoka"
   },
   {  
    "name":"The Poboys"
   },
   {  
    "name":"the shogun"
   },
   {  
    "name":"vinyard view"
   }
];
const cuisines = restaurants.reduce((result, restaurant ) => {
  if ( restaurant.hasOwnProperty( 'cuisine' )) {
    const { cuisine } = restaurant;
    if ( !result.hasOwnProperty( cuisine )) {
      result[ cuisine ] = {
        venueNames: []
      };
    }
    result[ cuisine ].venueNames.push( restaurant.name );
  }
  return result;
}, {});
console.log( cuisines );

在我个人看来,我会使用稍微不同的结构。如果我们用始终相同的对象表示集合,则可以简化大多数转换。这比在一个循环中完成所有操作效率低,但是用于创建转换的代码几乎是可读的英语:

代码语言:javascript
复制
const restaurants = [  
   { "name": "angelinas", "cuisine": null },
   { "name": "besuto", "cuisine": null },
   { "name": "catch", "cuisine": "japanese" },
   { "name": "center cut", "cuisine": null },
   { "name": "fedora", "cuisine": null },
   { "name": "habanero", "cuisine": "mexican" },
   { "name": "Indies", "cuisine": null },
   { "name": "new", "cuisine": null },
   { "name": "RazINN", "cuisine": null },
   { "name": "restaurantTestVenue779", "cuisine": null },
   { "name": "restaurantTestVenue9703", "cuisine": null },
   { "name": "Salsa ", "cuisine": "mexican" },
   { "name": "Sushi Place", "cuisine": "japanese" },
   { "name": "The Ashoka", "cuisine": null },
   { "name": "The Poboys", "cuisine": null },
   { "name": "the shogun", "cuisine": null },
   { "name": "vinyard view", "cuisine": null }
];
const create_cuisine = name => ({ name, "venues": [] });
const unique = () => {
  const seen = {};
  return item => {
    const json = JSON.stringify( item );
    return seen.hasOwnProperty( json )
      ? false
      : ( seen[ json ] = true );
  };
};
// Filter away all the restaurants without a cuisine value.
const restaurants_with_cuisine = restaurants.filter( restaurant => restaurant.cuisine );		
const cuisines = restaurants_with_cuisine
  // Extract the cuisine anmes from the restaurants.
  .map( restaurant => restaurant.cuisine )
  // Filter aways all the duplicates.
  .filter( unique() )
  // Create a new cuisine object.
  .map( cuisine_name => create_cuisine( cuisine_name ));
// Finally add all the restaurant names to the right cuisine.
restaurants_with_cuisine.forEach( restaurant => cuisines.find( cuisine => cuisine.name === restaurant.cuisine ).venues.push( restaurant.name ));

console.log( cuisines );

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52444448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档