它从后端获取具有非常特定键的对象。我必须更改一些值 \xe2\x80\x8b\xe2\x80\x8b 但仅限于我应该中断的属性。但是,我必须保持顺序。\n下面的代码可以工作,但我的项目中有问题 - 不同的浏览器?不知道。“For of”从键“14D”开始。我如何确定,如何维持秩序?由于特定的键,我无法对其进行排序。
\nlet updatedData = {};\nconst dataFromBd = {\n \'1M\': {\n name: \'anna\'\n },\n \'1Y\': {},\n \'2Y\': {},\n \'3M\': {},\n \'3Y\': {},\n \'4Y\': {},\n \'5Y\': {},\n \'6M\': {},\n \'7Y\': {},\n \'10Y\': {},\n \'14D\': {},\n \'15Y\': {},\n \'>20Y\': {}\n};\n\nfor (let [key, value] of Object.entries(dataFromBd)) {\n updatedData[key] = \'hello\';\n if (key === \'10Y\') break;\n}\n\nconsole.log(\'data\', updatedData);Run Code Online (Sandbox Code Playgroud)\r\n如果需要顺序,请使用数组,而不是对象。或者有时使用Map.
然而 -
下面的代码有效,但我的项目有问题 - 不同的浏览器?不知道。
只要您的键采用您所显示的样式,该代码将继续在任何符合标准的 JavaScript 引擎上运行,但请注意,顺序Object.entries只是最近定义的。自 ES2015 以来,JavaScript 就对对象属性有了一定的顺序,但直到最近,该顺序才应用于for-in、Object.keys、Object.values或Object.entries。
对于名称为非整数索引字符串的属性,顺序是属性创建的顺序。因此,由于您按照您想要的顺序创建属性,因此它们将按该顺序排列。
但是:以这种方式依赖属性顺序是很微妙的,我不推荐它。例如,如果在某个阶段,您的一个属性名称变成"42"而不是诸如 之类的名称"1M",那么它将中断,因为这是一个整数索引字符串属性名称,因此它在顺序中的位置不是基于它的创建时间,而是基于它的数值。
这是一个例子:
const obj1 = {
"1M": 1,
"0J": 2,
"1Q": 3,
};
// This is reliably ["1M", "0J", "1Q"] on up-to-date standard-compliant implementations:
console.log(Object.keys(obj1).join(", "));
const obj2 = {
"1M": 1,
"42": 2, // <=== Note the name is different
"1Q": 3,
};
// This is reliably ["42", "1M", "1Q"] on up-to-date standard-compliant implementations:
console.log(Object.keys(obj2).join(", "));
// Notice how "42" jumped to the beginning of the listRun Code Online (Sandbox Code Playgroud)
数组是有序的,因此使用对象数组当然可以可靠地工作。这是上面使用数组数组的示例(或者它可以是带有keyandvalue等的对象数组):
const array1 = [
["1M", 1],
["0J", 2],
["1Q", 3],
];
// This is reliably ["1M", "0J", "1Q"] on up-to-date standard-compliant implementations:
console.log(array1.map(([key]) => key).join(", "));
const array2 = [
["1M", 1],
["42", 2], // <=== Note the name is different
["1Q", 3],
];
// This is reliably ["1M", "42", "1Q"] on up-to-date standard-compliant implementations:
console.log(array2.map(([key]) => key).join(", "));
// Notice that "42" did NOT jump to the beginningRun Code Online (Sandbox Code Playgroud)
Map代替与对象不同,a 中的条目顺序Map纯粹按照插入顺序定义,而与键的值无关。Map此保证自 ES2015 中引入以来一直存在。
这是上面使用的示例Map:
const map1 = new Map([
["1M", 1],
["0J", 2],
["1Q", 3],
]);
// This is reliably ["1M", "0J", "1Q"] on up-to-date standard-compliant implementations:
console.log([...map1.keys()].join(", "));
const map2 = new Map([
["1M", 1],
["42", 2], // <=== Note the name is different
["1Q", 3],
]);
// This is reliably ["1M", "42", "1Q"] on up-to-date standard-compliant implementations:
console.log([...map2.keys()].join(", "));
// Notice that "42" did NOT jump to the beginningRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4399 次 |
| 最近记录: |