Converting an object into an array

Viewed 54

I have an object that contains other objects, as well as a few numbers i don't want.

I want to convert the object into an array of objects and remove the numbers.

an example:

INPUT

const object = {

  john: {
    instrument: 'violin',
    age: 26
  },

  bob: {
    instrument: 'guitar',
    age: 32
  },

  numberIDontWant: 2,

  flynn: {
    instrument: 'piano',
    age: 3
  },

  numberIDontWant2: 9
}

OUTPUT

  [
    {
      name: 'john',
      instrument: 'violin',
      age: 26
    },
    {
      name: 'bob',
      instrument: 'guitar',
      age: 32
    },
    {
      name: 'flynn',
      instrument: 'piano',
      age: 20
    }
  ]

Can anyone help me with that?

9 Answers

You could use Object.entries and .map:

console.log(Object.entries({
  john: {
    instrument: 'violin',
    age: 26
  },

  bob: {
    instrument: 'guitar',
    age: 32
  },

  numberIDontWant: 2,

  flynn: {
    instrument: 'piano',
    age: 3
  },

  numberIDontWant2: 9
}).map(([k,v]) => typeof v === 'object' ? ({...v, name: k}) : undefined).filter(i => i))

You'll most likely want to iterate over the Object.entries() so you have access to the key (the name) and the value. It isn't 100% clear what the criteria is for what values to include/exclude, but one way would be to only include the values that have a typeof equal to 'object'.

function objectToArray(obj) {
    let arr = [];
    for (let [name, value] of Object.entries(obj)) {
        if (typeof value === "object") {
            arr.push({
                ...value,
                name,
            });
        }
    }

    return arr;
}

console.log(
    objectToArray({
        john: {
            instrument: "violin",
            age: 26,
        },

        bob: {
            instrument: "guitar",
            age: 32,
        },

        numberIDontWant: 2,

        flynn: {
            instrument: "piano",
            age: 3,
        },

        numberIDontWant2: 9,
    })
);

You could use map and filter

const data = {
  john: {
    instrument: 'violin',
    age: 26
  },
  bob: {
    instrument: 'guitar',
    age: 32
  },
  numberIDontWant: 2,
  flynn: {
    instrument: 'piano',
    age: 3
  },
  numberIDontWant2: 9
}

const result = Object.entries(data).map(([k, v]) => {
    if (typeof v === "object") return { ...v, name: k }
}).filter(x => x);

console.log(result);

You iterate over all the keys and their values of your object. If the value is itself an object (typeof value === 'object' && value != null), you add a new object with the key as name and the object's values to the array.

const array = []

for (const [key, value] of Object.entries(object)) {
    if (typeof value === 'object' && value != null) {
        array.push({
            name: key,
            instrument: value.instrument,
            age: value.age
        })
    }
}

I would do it like this:

const object = {
  john: {
    instrument: 'violin',
    age: 26
  },

  bob: {
    instrument: 'guitar',
    age: 32
  },

  numberIDontWant: 2,

  flynn: {
    instrument: 'piano',
    age: 3
  },

  numberIDontWant2: 9
}

const result = [];

for (const i of Object.entries(object)) {
    if (typeof i[1] == 'object') {
    
        const obj = { name: i[0], ...i[1] }
        result.push(obj)
    }
    
}


console.log(result);

 

   const object = {
  john: {
    instrument: "violin",
    age: 26,
  },

  bob: {
    instrument: "guitar",
    age: 32,
  },

  numberIDontWant: 2,

  flynn: {
    instrument: "piano",
    age: 3,
  },

  numberIDontWant2: 9,
};

const arr = [];
for (let [key, value] of Object.entries(object)) {
  if (
    typeof value === "object" &&
    value.hasOwnProperty("instrument") &&
    value.hasOwnProperty("age")
  )
    arr.push({
      name: key,
      ...value,
    });
}
console.log(arr);

const object = {
  john: {instrument: 'violin', age: 26},
  bob: {instrument: 'guitar', age: 32},
  numberIDontWant: 2,
  flynn: {instrument: 'piano', age: 3},
  numberIDontWant2: 9
};

const result = Object.entries(object).reduce((arr, [k, v]) => 
  (typeof v === "object" && arr.push({...v, name:k}), arr)
, []);

console.log(result);

flatMap can be used to filter and map in one go, saving the need to call reduce.

I would use it like this:

const convert = (o) => 
  Object.entries(o).flatMap(([name, val]) => typeof val == 'object' ? [{name, ...val}] : [])

const object = {john: {instrument: 'violin', age: 26}, bob: {instrument: 'guitar', age: 32}, numberIDontWant: 2, flynn: {instrument: 'piano', age: 3}, numberIDontWant2: 9}

console.log(convert(object))
.as-console-wrapper {max-height: 100% !important; top: 0}

As you want to convert input object into an array of objects without properties which contains numbers. You can simply achieve it with a single line of code by using Array.filter() along with Array.map() method.

Demo :

const obj = {
  john: {
    instrument: 'violin',
    age: 26
  },
  bob: {
    instrument: 'guitar',
    age: 32
  },
  numberIDontWant: 2,
  flynn: {
    instrument: 'piano',
    age: 3
  },
  numberIDontWant2: 9
};

const res = Object.keys(obj).filter(item => typeof obj[item] === 'object').map(key => obj[key]);

console.log(res);

Related