【问题标题】:Get from JSON object with string IDs to JS numeric IDs [duplicate]从带有字符串 ID 的 JSON 对象获取到 JS 数字 ID [重复]
【发布时间】:2019-02-12 11:54:55
【问题描述】:

我有一个 JSON 对象(从 php 发送),我想使用 JS 将 ID 转换为数字键。所以目前它看起来像这样: let foo = {"66":"test","65":"footest"};

现在我希望它看起来像这样:

let foo = {66:"test",65:"footest"};

【问题讨论】:

  • 无论如何,键都是字符串,即使您没有在数字周围加上引号。
  • 请描述您的问题

标签: javascript php json


【解决方案1】:

访问对象键不需要是数字 - 如 cmets 中所述 - 它们无论如何都是字符串。 - 下面,我在控制台使用方括号表示法记录“66”属性 - foo[66]

let foo = {"66":"test","65":"footest"};

console.log(foo[66]); // gives "test"


// if you want to assign values numerically - ie using the index of a loop - then you could do
for(i = 63; i<65; i++) {
  foo[i] = "test" +  i;
}
console.log(foo); // gives {"63": "test63", "64": "test64","65": "footest","66": "test"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 2021-11-07
    • 1970-01-01
    • 2015-02-08
    • 2010-10-24
    • 2021-06-17
    • 2011-01-16
    相关资源
    最近更新 更多