Reputation: 9369
I have an object of array's like so:
{
"numbers": [
{"id":"11111"},
{"id":"22222"}
],
"letters": [
{"id":"aaaaa"},
{"id":"bbbbb"},
{"id":"33333"}
]
}
I'd like to figure out how to move id: 33333 from the letters object to the numbers object.
The only want I know how to move things is within it's own "dimension" using the .move(old_index, new_index)
Could anyone help me out to move from a different dimension?
I know a possible way would be to cycle through each item in the array, look for the specific id, and then push it to the other array and delete it from the previous one but I am trying to see if there is a better way.
Upvotes: 0
Views: 398
Reputation: 18753
// 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');
}
Find object by id in array of javascript objects from there simply use the same javascript code to remove from one array and push (add) into the other
Upvotes: 1
Reputation: 6988
First, your numbers and letters properties are actually arrays, not objects.
Since they are arrays, and id:33333
is the last element in the letters array, you can use .pop()
to remove it.
I don't know what the parent object is named, but you can do something like:
parentObject.numbers.push(parentObject.letters.pop())
Are you looking for a more programmatic way to do this? What if the elements you want to move are not the last element in the array? Let me know and I'll keep going.
EDIT:
So if you're trying to remove values from an array that aren't at the beginning or end (ie: .shift()
or .pop()
), then you can use .splice()
to remove the elements from any point in the array.
For instance: [1,2,3,4,5].splice(0,2)
will return a new array containing the removed elements: [1,2]
You can then append this spliced array to the target array using .concat()
, as in:
var selectedElements = [1,2,3,4,5].splice(0,2);
var targetArray = ['a', 'b', 'c'].concat(selectedElements);
This would return the targetArray
with the selected elements attached to it, ie:
targetArray = ['a', 'b', 'c', 1, 2]
Upvotes: 1