简体   繁体   English

从 2 个 json 文件中获取具有 React 条件的值

[英]Get values from 2 json files with condition in React

I have 2 json files statesCode.json and cityAndzipCode.json having following structure我有 2 个 json 文件 statesCode.json 和 cityAndzipCode.json 具有以下结构

statesCode.json statesCode.json

{ "Alabama" : "AB" ,
 "Alaska" : "AS" ,
 }

cityAndzipCode.json cityAndzipCode.json

{ "Alabama" : { city : "Birmingham" , zipcode : "123456" },
 "Alaska" : { city : "Anchorage" , zipcode : "453567" }, 
---
 }

now in my component I am returning stateAbbreviation, cityName and zipCode.现在在我的组件中,我返回 stateAbbreviation、cityName 和 zipCode。 I have to write a condition that if we get only stateAbbreviation in url and cityName and zipCode are null, then we have to check the list in cityAndzipCode.json and return city and zipCode as array.我必须写一个条件,如果我们只得到 url 中的 stateAbbreviation 并且 cityName 和 zipCode 是 null,那么我们必须检查 cityAndzipCode.Z466DEEC76ECDF5FCA6D38571F6Z34 中的列表并返回数组。

I was able to apply this logic, kindly tell me what am I doing wrong我能够应用这个逻辑,请告诉我我做错了什么

if ( url . zipCode === null && url.cityName === null && url . stateAbbreviation )
 { 
 if ( url . stateAbbreviation === stateCodes ) {
 url . cityName = stateCodes ;
 url . zipCode = stateCodes [ 1 ];
 } 

I am beginning with a hope that your data looks like as below:我开始希望您的数据如下所示:

stateCodes = { 
  "Alabama": "AB" ,
  "Alaska": "AS" ,
};
      
cityAndzipCode = { 
  "Alabama": { city : "Birmingham" , zipcode : "123456" },
  "Alaska": { city : "Anchorage" , zipcode : "453567" }, 
 };

url = { cityName:null, zipCode:null, stateAbbreviation:'AB' };

if (!url.zipCode && !url.cityName && url.stateAbbreviation) { 
  const index = Object.values(stateCodes).indexOf(url.stateAbbreviation);  
  const value = Object.keys(stateCodes)[index];
  if (value) {
    url.cityName = cityAndzipCode[value].city;
    url.zipCode = cityAndzipCode[value].zipcode;
  } 
}

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

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