如何列出对象,包括值,名称,面额?

时间:2018-11-16 14:37:37

标签: javascript object

我有一个这样的对象:

  var currencyTypes = {
    NOK: {value:1.00000, name: "Norske kroner", denomination: "kr" },
    EUR: {value:0.10733, name: "Europeiske euro", denomination: "€" },
    USD: {value:0.12652, name: "United States dollar", denomination: "$" },
    GBP: {value:0.09550, name: "Pound sterling", denomination: "£" },
  };

我找到了列出所有关键对象的方法:

var keyVal = [];
for(var v in currencyTypes) keyVal.push(v);

"There are " + keyVal.length + " different currencies here: " + keyVal

这会列出所有货币类型:NOK,EUR,USD,GBP

但是如何打印带有键,值,名称,面额的列表?我尝试了keyVal.properties,但是没有用。我试图在这里搜索解决方案,但没有找到任何东西。我想要的是看起来像这样的输出:

NOK, Norske kroner, 1 kr
EUR, European euros, 0.10733 €
and so on

6 个答案:

答案 0 :(得分:1)

您可以通过这种方式访问​​它。 might可以为您提供帮助。

 var currencyTypes = {
    NOK: {value:1.00000, name: "Norske kroner", denomination: "kr" },
    EUR: {value:0.10733, name: "Europeiske euro", denomination: "€" },
    USD: {value:0.12652, name: "United States dollar", denomination: "$" },
    GBP: {value:0.09550, name: "Pound sterling", denomination: "£" },
  };
  
  for(var type in currencyTypes)
  {
    console.log("Currency: " + type);
    
    console.log("Value: " + currencyTypes[type].value);
    console.log("Name: " + currencyTypes[type].name);
    console.log("Denomination: " + currencyTypes[type].denomination);
    
    console.log("\n");
  }

答案 1 :(得分:1)

const currencyTypes = {
    NOK: {value:1.00000, name: "Norske kroner", denomination: "kr" },
    EUR: {value:0.10733, name: "Europeiske euro", denomination: "€" },
    USD: {value:0.12652, name: "United States dollar", denomination: "$" },
    GBP: {value:0.09550, name: "Pound sterling", denomination: "£" },
};

function compileCurrenciesString(currencies) {
  let outStr = '';
  Object.keys(currencies).forEach((key) => {
    outStr += currencyToString(key, currencies[key]);
    outStr += '\n';
  });
  return outStr;
}

function currencyToString(key, currency) {
  return `${key}, ${currency.name}, ${currency.value} ${currency.denomination}`;
}

console.log(compileCurrenciesString(currencyTypes));

答案 2 :(得分:0)

您可以使用if(200){isRequestWebOk = YES;}检索所有对象键,然后在这些对象上循环:

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType{
    static BOOL isRequestWeb = YES;
    static BOOL isRequestWebOk = NO;
    NSString *embedHTML = @"<html><head></head><body style='color:#000;'><p>Error</p></body></html>";

    if (isRequestWeb) {
        //NSHTTPURLResponse *response = nil;
        //NSData *data = [NSURLConnection sendSynchronousRequest:inRequest returningResponse:&response error:nil];
        //if (response.statusCode == 404) {}

        [[[NSURLSession sharedSession] dataTaskWithRequest:inRequest completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSInteger statusCode = httpResponse.statusCode;
            if (statusCode >= 200 && statusCode < 300){
                /*I think this do set but i can't access it outside the completionHandler but i really need to check it outside as i cannot do many other things inside here*/
                isRequestWebOk = YES;
                NSLog(@"GOOD");
            }else if (statusCode == 404) {
                NSLog(@"code for 404");
            }else if (statusCode == 403) {
                NSLog(@"code for 403");
            }else if (statusCode == 500) {
                NSLog(@"code for 500");
            }else{
                NSLog(@"code for ALL");
                isRequestWebOk = YES;
            }
            NSLog(@"code is what: %ld", (long)statusCode);
        }] resume];
        isRequestWeb = NO;

        /*This is where am checking for isRequestWebOk if true or not but it always return false*/
        if(isRequestWebOk){
            NSLog(@"Request is okay 200");
            return YES;
        }else{
            NSLog(@"Bad Request b4004");
            inWeb.userInteractionEnabled = NO;
            inWeb.opaque = NO;
            inWeb.backgroundColor = [UIColor clearColor];
            [inWeb loadHTMLString: embedHTML baseURL: nil];
            return NO;
        }
    }
    return YES;
}

答案 3 :(得分:0)

您可以对for...of使用Object.entries循环来获取key value

var currencyTypes = { NOK: {value:1.00000, name: "Norske kroner", denomination: "kr" }, EUR: {value:0.10733, name: "Europeiske euro", denomination: "€" }, USD: {value:0.12652, name: "United States dollar", denomination: "$" }, GBP: {value:0.09550, name: "Pound sterling", denomination: "£" }};
  
for([key, {name, value, denomination}] of Object.entries(currencyTypes)) {
  let str = `${key}, ${name}, ${value} ${denomination}`
  console.log(str)
}

答案 4 :(得分:0)

如果您将集合表示为数组,则执行此类操作会变得更加容易:

const currencyTypes = [
  { "ticker": "NOK", "value":1.00000, "name": "Norske kroner", "denomination": "kr" },
  { "ticker": "EUR", "value":0.10733, "name": "Europeiske euro", "denomination": "€" },
  { "ticker": "USD", "value":0.12652, "name": "United States", "denomination": "$" },
  { "ticker": "GBP", "value":0.09550, "name": "Pound sterling", "denomination": "£" }
];
//  Amount of currencies:
console.log( 'There are ' + currencyTypes.length + ' currencies in the array' );
//  Array of all currency tickers:
console.log( currencyTypes.map( currency => currency.ticker ));
//  Console.logging all of them:
currencyTypes.forEach( currency => console.log( currency ));
//  Console.logging the properties using destructuring:
currencyTypes.forEach(({ ticker, value, name, denomination }) => console.log( ticker, value, name, denomination ));

当您拥有多个对象时,通常是最简单的方法,因为大多数表示集合的对象都可以在一行代码中从数组中创建。

如果您想继续使用对象,请查看Object.keys()Object.values()Object.entries()。这些将完成从对象到数组的来回转换。

您为获取对象中键的数量而编写的函数基本上与Object.keys()相同:

const currencyTypes = {
  NOK: {value:1.00000, name: "Norske kroner", denomination: "kr" },
  EUR: {value:0.10733, name: "Europeiske euro", denomination: "€" },
  USD: {value:0.12652, name: "United States dollar", denomination: "$" },
  GBP: {value:0.09550, name: "Pound sterling", denomination: "£" },
};
  
console.log( 'there are ' + Object.keys( currencyTypes ).length + ' currencies' );

答案 5 :(得分:0)

如果您要按照ES6规范进行编码,则可以使用destructuring assignment

我还利用Object.entries方法将对象属性转换为键值条目对数组-然后使用Array.prototype.forEach对其进行迭代。

var currencyTypes = {
  NOK: {
    value: 1.00000,
    name: "Norske kroner",
    denomination: "kr"
  },
  EUR: {
    value: 0.10733,
    name: "Europeiske euro",
    denomination: "€"
  },
  USD: {
    value: 0.12652,
    name: "United States dollar",
    denomination: "$"
  },
  GBP: {
    value: 0.09550,
    name: "Pound sterling",
    denomination: "£"
  },
};

Object.entries(currencyTypes).forEach(entry => {
  const [key, val] = entry;
  const {
    value,
    name,
    denomination
  } = val;
  console.log(`${key}\n${value}\n${name}\n${denomination}`);
});