javascript - 拼接数组中的嵌套对象

标签 javascript arrays object splice

我正在尝试找到一种简单的方法来将对象从嵌套数组中移出并将其移至其父数组。我不断收到“splice is not a function”,如果您尝试使用“moveItem()”函数,您会看到这一点。我不知道如何重写它才能工作,如果它甚至被允许做这件事的话。任何帮助表示赞赏。简而言之,我正在尝试将对象从 items[0].contains[] 移动到 items[] 希望这是有道理的。

var items = [{
  itemIndex: 0,
  name: "a box of matches",
  examine: "The box is old and damp,you find a single match inside.",
  location: 0, // if location === 1000, items is in inventory.
  contains: [{
    itemIndex: 1,
    name: "a match",
    examine: "A single match.",
    location: 0,
    contains: [],
    hidden: true,
    collectable: true,
    useWith: 2,
    useWithFail: 0,
    useWithFailResponse: "the box is too damp to light the match",
    useWithSuccessResponse: null
  }], // Contain items inside items using array.
  hidden: false, // if hidden, item cannot show up in invetory or room inventory
  collectable: true,
  useWith: null, // Item that this item can be successfully used with - index or null
  useWithFail: 1, // Use with item that fails but has it's own unique fail message - index or null
  useWithFailResponse: "the box is too damp to light the match",
  useWithSuccessResponse: null
}, {
  itemIndex: 2,
  name: "a closed cupboard",
  examine: "You find a kitchen knife inside",
  location: 4,
  contains: [],
  hidden: false,
  collectable: false,
  useWith: null,
  useWithFail: null,
  useWithFailResponse: null,
  useWithSuccessResponse: "The match spaks into life!"
}, {
  itemIndex: 3,
  name: "a kitchen knife",
  examine: "It is old and rusty.",
  location: 4,
  contains: [],
  hidden: true,
  collectable: true,
  useWith: 1,
  useWithFail: null,
  useWithFailResponse: null,
  useWithSuccessResponse: "The match sparks into life!"
}, ];

function moveItem() {
  items.push(items[0].contains[0].splice(0, 1));
}

最佳答案

Array.prototype.splice() 返回

An array containing the deleted elements.

要将某个对象从嵌套数组向上移动到父级别,请使用以下方法:

items.push(items[0].contains.splice(0, 1)[0]);

关于javascript - 拼接数组中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41872745/

相关文章:

javascript - 为什么当我尝试对列表进行排序时单击按钮时 list.js 不起作用

javascript - 清空用户的 HTTP_REFERER 最可靠的方法是什么?

javascript - 延迟加载自定义绑定(bind)

javascript - "[object Object]"中小写字母与大写字母所暗示的控制台区别

javascript - 即使使用 Vue.set ,更新数组也不会在 Vue 中重新渲染

javascript - 如何将命令行参数传递给 v8 中的脚本?

python:连接两个2维numpy数组以创建3维数组

java - 读取文本文件并将其拆分为数组 - Android

php - 通过单击按钮填充 PHP 数组

javascript - 仅使用 for 循环来迭代对象数组与其他数组