我在reactjs项目中工作,我有一个小问题!
我需要用从输入框中插入的值替换模型json的值。
这是我的模型json:
import UIKit
import CoreData
class ResultsTableController: UITableViewController {
var filteredCities = [Zone]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "searchResultsCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredCities.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchResultsCell", for: indexPath)
if let city = filteredCities[indexPath.row].cityName {
if let country = filteredCities[indexPath.row].countryName {
cell.textLabel?.text = "\(city.replacingOccurrences(of: "_", with: " ")), \(country)"
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCity = filteredCities[indexPath.row]
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let originalUrl = "http://vip.timezonedb.com/v2.1/get-time-zone?key=\(apiKey)&format=json&by=city&city=\(selectedCity.cityName!)&country=\(selectedCity.countryCode!)"
if let encodedUrl = URL(string: originalUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!) {
print(encodedUrl)
let task = session.dataTask(with: encodedUrl) { data, response, error in
// Check for errors
guard error == nil else {
print ("error: \(error!)")
return
}
// Check that data has been returned
guard let content = data else {
print("No data")
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let fetchedData = try decoder.decode(TimeZones.self, from: content)
if let city = fetchedData.zones?.first {
DispatchQueue.main.async {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
let savedCity = SavedCity(context: context)
if let offSet = city.gmtOffset {
savedCity.formattedDate = city.formatted!.components(separatedBy: " ").first!
savedCity.formattedTime = city.formatted!.components(separatedBy: " ").last!
savedCity.formatted = city.formatted
savedCity.countryCode = city.countryCode
savedCity.formattedCityName = city.zoneName!.components(separatedBy: "/").last!
savedCity.countryName = city.countryName
savedCity.gmtOffset = Int32(offSet)
savedCity.zoneName = city.zoneName
savedCity.cityName = city.cityName
}
// Save to core data
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
}
} catch let err {
print("Err", err)
}
}
// execute the HTTP request
task.resume()
self.dismiss(animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
let vc = TimeZonesTable()
vc.refreshData()
}
}
这是当数据可能不完整时从输入框接收的数据:
const createGdd = [
{
documentTypeId: 'SE',
userName: 'POSTMAN',
deviceUserAs400: 'WEB(CHROME,192.168.34.4)',
emissionDate: 1575244800000,
emitterStoreId: 12,
receiver: {
dni: '0096293000',
dniVerifyDigit: 'K',
description: 'EPSON PERU S.A.',
economicActivityCode: 'GENERICO',
address: {
city: 'MANZANA',
commune: 'PERA',
description: 'AVDA.ANDRES SINO N.2287',
},
storeId: 0,
},
totalNetAmount: 94570,
totalAmount: 112538,
taxRate: 19,
taxAmount: 19,
details: [],
others: {},
},
]
这是最终的json:
{
"emitterStoreId": 9,
"receiver": {
"storeId": 0,
"address": {}
},
"others": {
"applicantBy": "Hernán",
"packages": {
"packageAmount": 2
},
"driverLastName": "Juan",
"dispatcherName": "IC23S0"
},
"details": [
{
"sku": 1,
"quantity": 1,
"description": "Bolsas de color rojo ",
"netPrice": 200,
"amount": 1
},
{
"sku": 1,
"quantity": 2,
"description": "Bolsas de color negra",
"netPrice": 400,
"amount": 1
}
]
}
]
你知道这个问题的一些技术吗?
谢谢!
答案 0 :(得分:-1)
首先,您的createGdd对象在此处格式错误:
const createGdd = [
{
documentTypeId: 'SE',
userName: 'POSTMAN',
deviceUserAs400: 'WEB(CHROME,192.168.34.4)',
emissionDate: 1575244800000,
emitterStoreId: 12,
receiver: {
dni: '0096293000',
dniVerifyDigit: 'K',
description: 'EPSON PERU S.A.',
economicActivityCode: 'GENERICO',
address: {
city: 'MANZANA',
commune: 'PERA',
description: 'AVDA.ANDRES SINO N.2287',
},
storeId: 0,
},
totalNetAmount: 94570,
totalAmount: 112538,
taxRate: 19,
taxAmount: 19,
details: [],
others: {},
},//<-- delete that extra comma
];
如果要向元素添加明细子集,只需将原始对象复制到新元素中,然后推送数据;
const createGdd = [
{
documentTypeId: 'SE',
userName: 'POSTMAN',
deviceUserAs400: 'WEB(CHROME,192.168.34.4)',
emissionDate: 1575244800000,
emitterStoreId: 12,
receiver: {
dni: '0096293000',
dniVerifyDigit: 'K',
description: 'EPSON PERU S.A.',
economicActivityCode: 'GENERICO',
address: {
city: 'MANZANA',
commune: 'PERA',
description: 'AVDA.ANDRES SINO N.2287',
},
storeId: 0,
},
totalNetAmount: 94570,
totalAmount: 112538,
taxRate: 19,
taxAmount: 19,
details: [],
others: {},
}
];
let details = {
"emitterStoreId": 9,
"receiver": {
"storeId": 0,
"address": {}
},
"others": {
"applicantBy": "Hernán",
"packages": {
"packageAmount": 2
},
"driverLastName": "Juan",
"dispatcherName": "IC23S0"
},
"details": [
{
"sku": 1,
"quantity": 1,
"description": "Bolsas de color rojo ",
"netPrice": 200,
"amount": 1
},
{
"sku": 1,
"quantity": 2,
"description": "Bolsas de color negra",
"netPrice": 400,
"amount": 1
}
]
};
let element = JSON.parse(JSON.stringify(createGdd));
console.log("original object",createGdd)
element[0].details.push(details);
console.log("desired output",element);
希望有帮助