typeof value is "object" for array in key value in javascript. Cannot perform array operations on it

Viewed 34

Note: Do guide me if something is missing.

Let's say we have an object:

let obj = {
    d:[1,2],
    e:[2,4]
}

Doing Object.values(obj)[0] returns [1,2] but as an object but operations cannot be performed on them. Is there any generic way for accessing the value as an array for doing something like sending it to another function? I have tried pushing it into an array but it nests the array (e.g. [1,2]) it 2 times in the pushed array.

Edit:

When this below function is passed to subtract function, it returns Nan:

function solveThis(object) {
    let result=[]
    for (i=0;i<Object.keys(object).length;i++) {

        if (Object.keys(object)[i]=="sum")
            result.push(sum(Object.values(object)[i]))
        if (Object.keys(object)[i]=="multiply")
            result.push(multiply(Object.values(object)[i]))
        if (Object.keys(object)[i]=="subtract")
            result.push(subtract(Object.values(object)[i]))

    }
    return result
}
console.log(solveThis({subtract:[3,3]}))

function subtract(a,b) {
    return a-b;
}

1 Answers

Lots of things are objects in JavaScript, including arrays, IIRC.

Object.values(obj)[0] gives you the first array in your original object and you can use it as such, e.g.:

let array = Object.values(obj)[0];
array.forEach((item) => {
  console.log(item);
});

This should output the following in your console:

1

2

Related