[英]Forming JSON with Key and Value if Key Exists
我有一個類似的JSON結構:
[
{
"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結構,例如:
[
{
"Mexican":{
"venueNames":[
"Habanero",
"Salsa"
]
}
},
{
"Japanese":{
"venueNames":[
"Sushi Place",
"catch"
]
}
}
]
嘗試使用for循環和.hasProperty構建JSON,但沒有成功。
這是您可以做的! 首先遍歷數據,然后使用方法“ hasOwnProperty”檢查該美食是否存在,是否存在,然后檢查您的美食對象是否具有該美食,然后將其添加到其中。
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]
};
}
}
}
這是對數組的簡單簡化。 如果餐廳有已定義的美食,請檢查結果是否已定義了該美食。 如果沒有,請為其創建一個對象,您可以將餐廳名稱推送到該對象。
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 );
我個人認為,我會使用略有不同的結構。 如果我們用始終相同的對象表示集合,則可以簡化大多數轉換。 這比在一個循環中完成所有操作效率低,但是用於創建轉換的代碼幾乎是可讀的英語:
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 );
您可以在下面的一個循環中使用。
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);
}
}
});
使用一些es6功能,我們可以使用Set , map和filter生成此列表。
我們將首先映射美食列表,並刪除無效的美食,例如undefined
。 這樣,我們將使用Set
來創建獨特的美食列表。
接下來,我們將通過過濾與烹飪與當前迭代匹配的原始對象,獲取該列表並將其再次映射以返回最終對象。 最后,我們將過濾后的結果映射為僅將名稱返回給venueNames
對象。
我們的結果將如下所示:
function getItems(places) { // Get a unique list of cuisines return [...new Set(places.map(p => p.cuisine).filter(c => c))] // Build the result .map(c => { return { [c]: { // Get a list of cuisines that match the current cuisine venueNames: places.filter(p => p.cuisine == c).map(c => c.name) } } }) } const places = [ {"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"} ] console.log(getItems(places))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.