gpt4 book ai didi

javascript - 按顺序获取 JSON 键

转载 作者:搜寻专家 更新时间:2023-11-01 04:30:00 25 4
gpt4 key购买 nike

我在文件中有以下内容并阅读为

var input = require("./mydata.json");

"User": {
"properties": {
"firstName": {
"type": "string",
"minLength": 1,
"maxLength": 50
},
"lastName": {
"type": "string",
"maxLength": 50
},
"middleName": {
"type": "string"
},
"title": {
"type": "string"
},
"language": {
"type": "string",
"default": "en-US"
}
}
}

我正在使用下面的代码来遍历键

var item = _.get(input, 'User');
var properties = item.properties;
var allKeys = _.keys(properties);
_.each(allKeys, function(key) {

});

在每个循环中,我按照与输入文件中相同的顺序获取名字、姓氏等。我想知道我是否总能把它整理好?

最佳答案

JavaScript 不保证对象中的属性顺序;您需要使用 Array 来保存它。

对象的定义来自 ECMAScript Third Edition (pdf) :

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

自 ECMAScript 2015,使用 the Map object可能是另一种选择。 MapObjectguarantees the keys order 有一些相似之处。 :

A Map iterates its elements in insertion order, whereas iteration order is not specified for Objects.

关于javascript - 按顺序获取 JSON 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com