Javascript 在对象之间移动数组项

标签 javascript jquery arrays

我有一个数组对象,如下所示:

{
    "numbers": [
        {"id":"11111"},
        {"id":"22222"}
    ],
    "letters": [
        {"id":"aaaaa"},
        {"id":"bbbbb"},
        {"id":"33333"}
    ]
}

我想弄清楚如何将 id: 33333字母对象移动到数字对象。

我唯一想要知道如何移动东西是在它自己的“维度”内使用.move(old_index, new_index)

有人可以帮我从不同的维度移动吗?

我知道一种可能的方法是循环遍历数组中的每个项目,查找特定的 id,然后将其推送到另一个数组并将其从前一个数组中删除,但我想看看是否有一个更好的方法。

最佳答案

jsFiddle使用纯 JavaScript

// your object
var o = {
    "numbers": [
        {"id":"11111"},
        {"id":"22222"}
    ],
    "letters": [
        {"id":"aaaaa"},
        {"id":"bbbbb"},
        {"id":"33333"}
    ]
};

// gets the index
// a = the array to look in
// p = the property to check
// v = the value you are looking for
function getIndex(a, p, v) {
    for(var i=0; i < a.length; i++) {
        if(a[i][p] == v) {
            return i;
        }
    }
}

// get the index from the letters array with property 'id' with value '33333'
var index = getIndex(o['letters'], 'id', '33333');
console.log(index);
// if you found the item
if (index !== undefined) {
    // get the actual item from the array
    var item = o['letters'][index];
    console.log(o['letters']);
    console.log(o['numbers']);
    console.log(item);
    // add the item to the other numbers array
    o['numbers'].push(item);
    // remove the item from the letters array
    o['letters'].splice(index, 1);
    console.log(o['letters']);
    console.log(o['numbers']);
} else {
    console.log('did not find the item');
}
<小时/>

使用 jQuery

Find object by id in array of javascript objects从那里只需使用相同的 JavaScript 代码从一个数组中删除并推送(添加)到另一个数组中

关于Javascript 在对象之间移动数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30463565/

相关文章:

javascript - 我可以使用 Chrome 扩展程序删除事件监听器吗?

javascript - 超链接(带有查询字符串)打开新窗口特定大小

javascript - React-highcharts-官方延迟加载数据

Jquery 窗口调整大小错误

arrays - 如何创建具有唯一 "character names"的数组?

JavaScript DOM : transfer element between frames

jquery - 错误 $ 未在 Angular Universal 中定义

javascript - 使用 knockout 将数组元素数据绑定(bind)为值

ios - 自定义 iOS ChartBar

java - 在数组前面添加一个字符