我有一个数组对象,如下所示:
{
"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/