为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

开满天机 2023-02-24 15:48:50
假设我有一个对象let data = { info_0: 'abc', info_1: 'def', info_2: 'ghi' }我从用户输入中收到了 1 的值。我需要..从对象中搜索并删除 info_1将 info_2 移动/重命名为 info_1应该是动态的你明白了,你从用户那里收到了索引。从对象中删除该键值对并调整/移动其中的每个键,使其看起来像一个从 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 : '' }
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

您可以将属性的值移动 1


let data = {

    info_0: 'abc',

    info_1: 'def',

    info_2: 'ghi',

    info_3: 'jkl',

    info_4: 'mno',

    info_5: 'pqr'

  },

  input = document.querySelector("#index"),

  button = document.querySelector("#remove"),

  output = document.querySelector("#output");


button.addEventListener("click", () => removeItem(+input.value));

refreshOutput();


function removeItem(index) {

  if (isNaN(index) || index < 0) return;

  index = Math.floor(index);

  while (data["info_" + index] !== undefined) {

    data["info_" + index] = data["info_" + ++index];

  }

  refreshOutput();

}


function refreshOutput() {

  output.textContent = JSON.stringify(data);

}

<input id="index" type="number" placeholder="index" />

<button id="remove">Remove</button>

<div id="output"></div>

您也可以使用delete运算符(效率很低)


let data = {

    info_0: 'abc',

    info_1: 'def',

    info_2: 'ghi',

    info_3: 'jkl',

    info_4: 'mno',

    info_5: 'pqr'

  },

  input = document.querySelector("#index"),

  button = document.querySelector("#remove"),

  output = document.querySelector("#output");


button.addEventListener("click", () => removeItem(+input.value));

refreshOutput();


function removeItem(index) {

  if (isNaN(index) || index < 0) return;

  index = Math.floor(index);

  while (("info_" + index) in data) {

    data["info_" + index] = data["info_" + ++index];

  }

  delete data["info_" + index];

  refreshOutput();

}


function refreshOutput() {

  output.textContent = JSON.stringify(data);

}

<input id="index" type="number" placeholder="index" />

<button id="remove">Remove</button>

<div id="output"></div>

或者你可以只使用一个数组和Array#splice


let data = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr'],

  input = document.querySelector("#index"),

  button = document.querySelector("#remove"),

  output = document.querySelector("#output");


button.addEventListener("click", () => removeItem(+input.value));

refreshOutput();


function removeItem(index) {

  if (isNaN(index) || index < 0) return;

  data.splice(Math.floor(index), 1);

  refreshOutput();

}


function refreshOutput() {

  output.textContent = JSON.stringify(data);

}

<input id="index" type="number" placeholder="index" />

<button id="remove">Remove</button>

<div id="output"></div>


查看完整回答
反对 回复 2023-02-24
  • 1 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信