简体   繁体   English

在数组中拼接嵌套对象

[英]Splice nested object in array

I'm trying to find a simple way to move an object from a nested array and move it to its parent array. 我试图找到一种简单的方法来将对象从嵌套数组中移动并将其移动到其父数组。 I keep getting "splice is not a function," as you can see if you try to use the 'moveItem()' function. 我不断收到“剪接不是函数”的信息,您可以看到是否尝试使用'moveItem()'函数。 I don't know how to re-write this so it works, if it's even allowed to do things this one. 我不知道该如何重写它,即使它被允许做这个事情也是如此。 Any help is appreciated. 任何帮助表示赞赏。 In short, I'm trying to move the object from items[0].contains[] to items[] Hope that makes sense. 简而言之,我正在尝试将对象从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() returns Array.prototype.splice()返回

An array containing the deleted elements. 包含已删除元素的数组。

To move a certain object from nested array up to the parent level use the following approach: 要将特定对象从嵌套数组移到父级,请使用以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM