关于调整/移动对象上的键值对的快速帮助

假设我有一个对象

let data = { info_0: 'abc', info_1: 'def', info_2: 'ghi' }

我从用户输入中收到了 1 的值。我需要..

  1. 从对象中搜索并删除 info_1

  2. 将 info_2 移动/重命名为 info_1

  3. 应该是动态的

你明白了,你从用户那里收到了索引。从对象中删除该键值对并调整/移动其中的每个键,使其看起来像一个从 0 到 X 的数组。(在本例中为 info_0 到 info_x)

我有一个很长的 for, if's & obj keys 循环解决方案。但我正在尝试学习一些捷径。非常感谢您的帮助

编辑: 对象还可能包含各种键的组合,例如:client_x、charges_x、description_x 等

{ info_0  : '', info_1  : '', client_0  : '', client_1  : '', client_2  : '', descpription_0 : '' }


开满天机
浏览 84回答 1
1回答

收到一只叮咚

您可以将属性的值移动 1let data = {&nbsp; &nbsp; info_0: 'abc',&nbsp; &nbsp; info_1: 'def',&nbsp; &nbsp; info_2: 'ghi',&nbsp; &nbsp; info_3: 'jkl',&nbsp; &nbsp; info_4: 'mno',&nbsp; &nbsp; info_5: 'pqr'&nbsp; },&nbsp; input = document.querySelector("#index"),&nbsp; button = document.querySelector("#remove"),&nbsp; output = document.querySelector("#output");button.addEventListener("click", () => removeItem(+input.value));refreshOutput();function removeItem(index) {&nbsp; if (isNaN(index) || index < 0) return;&nbsp; index = Math.floor(index);&nbsp; while (data["info_" + index] !== undefined) {&nbsp; &nbsp; data["info_" + index] = data["info_" + ++index];&nbsp; }&nbsp; refreshOutput();}function refreshOutput() {&nbsp; output.textContent = JSON.stringify(data);}<input id="index" type="number" placeholder="index" /><button id="remove">Remove</button><div id="output"></div>您也可以使用delete运算符(效率很低)let data = {&nbsp; &nbsp; info_0: 'abc',&nbsp; &nbsp; info_1: 'def',&nbsp; &nbsp; info_2: 'ghi',&nbsp; &nbsp; info_3: 'jkl',&nbsp; &nbsp; info_4: 'mno',&nbsp; &nbsp; info_5: 'pqr'&nbsp; },&nbsp; input = document.querySelector("#index"),&nbsp; button = document.querySelector("#remove"),&nbsp; output = document.querySelector("#output");button.addEventListener("click", () => removeItem(+input.value));refreshOutput();function removeItem(index) {&nbsp; if (isNaN(index) || index < 0) return;&nbsp; index = Math.floor(index);&nbsp; while (("info_" + index) in data) {&nbsp; &nbsp; data["info_" + index] = data["info_" + ++index];&nbsp; }&nbsp; delete data["info_" + index];&nbsp; refreshOutput();}function refreshOutput() {&nbsp; output.textContent = JSON.stringify(data);}<input id="index" type="number" placeholder="index" /><button id="remove">Remove</button><div id="output"></div>或者你可以只使用一个数组和Array#splicelet data = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr'],&nbsp; input = document.querySelector("#index"),&nbsp; button = document.querySelector("#remove"),&nbsp; output = document.querySelector("#output");button.addEventListener("click", () => removeItem(+input.value));refreshOutput();function removeItem(index) {&nbsp; if (isNaN(index) || index < 0) return;&nbsp; data.splice(Math.floor(index), 1);&nbsp; refreshOutput();}function refreshOutput() {&nbsp; output.textContent = JSON.stringify(data);}<input id="index" type="number" placeholder="index" /><button id="remove">Remove</button><div id="output"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript