Skip to content Skip to sidebar Skip to footer

Javascript Arrays Inside Object

i have a arrays inside object like this for example: {1: Array(4), 2: Array(4), 3: Array(4)} 1: (4) ['11111', '2020-04-02', '14:07', 1] 2: (4) ['22222', '2020-04-02', '14:07', 2] 3

Solution 1:

If you convert your object to an array-like then you can use array methods with it.

An array-like object basically needs a length property and keys that are positive integers. The length needs to be set to one more than the highest index. So, if you have keys 1, 2, 3 then you need length: 4. Yes, it's a bit misleading since there are only three elements but length is more accurately called "next available index".

At any rate, if you transform your object, then you can use Array#splice and set the target using Function#call. Most array methods are intentionally generic so they can work on anything that's an array-like:

const obj = {
  1: ["foo"],
  2: ["bar"],
  3: ["baz"],
  length: 4
}

//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)

console.log(obj);

Note how the indexes after the deleted one shifted and the length was also adjusted automatically.

If you don't know what the length is currently, you can easily find it:

const obj = {
  1: ["foo"],
  2: ["bar"],
  3: ["baz"]
}


const keys = Object
  .keys(obj)   //get all keys
  .map(Number) //convert to numbers
  .filter(key => Number.isInteger(key) && key >= 0); //leave only positive integers

//find the highest
const highestKey = keys.reduce((a, b) =>  Math.max(a, b), -1);

//set the length to the next possible index
obj.length = highestKey + 1;

//delete starting from index 2 and remove 1 item
Array.prototype.splice.call(obj, 2, 1)

console.log(obj);

Solution 2:

In the object above, when you delete the second array, only that key is removed and this has no impact on other keys. Because object keys act as an identifier to access the location of value corresponding to that key.

If you want that other keys should reset accoding to order. Please use array of arrays instead of objects having arrays as values.

Array - ordered items with numeral indices Object - unordered items with any valid string or number indices.

If it is required to use object, here's the solution to manually do it -

For the index i that needs to be removed, parse the next indices (numerically greater than i) to take key = key - 1, i.e., decreasing their index key by 1.

// index is treated from 1 to n.
const deleteElement = (delete_index, obj) => {
    const keyCount = Object.keys(obj).length;

    // move all elements with keys > delete_index to previous index
    for(let i=delete_index; i<=keyCount; i++) {
        obj[i] = obj[i+1]
    }
    // delete last element
    delete obj[keyCount]
}



Solution 3:

use splice methodarr.splice(2,1) where first argument is index and second will be number of items to remove from array.


Post a Comment for "Javascript Arrays Inside Object"