Create new array depending of the number of properties in another object in Javascript

Viewed 45

I have an object and depending of the number of properties in that, I need to create a new array.

const data = {
    name: 'John Doe',
    company:'Google'
}

So, the new array should be like this:

const array = [
    0: {
        id: 3434,
        fileId: name, //from data
        criter: 'John Doe;
        address: '12345'
    }
    1: {
        id: 4233,
        fileId: company, //from data
        criter: 'Google;
        address: '32344'
    }
]

I have tried to create array and to use Object.keys and Object.values to get the data, but I'm not achieving this.

 const testArray = [{
    criter: Object.values(data).map(key => key),
    fileId: Object.keys(data).map(key => key)',
  }];
2 Answers

Object.entries() will help here

const data = {
  name: 'John Doe',
  company: 'Google'
}

var resultObj = Object.entries(data).map(function(keyvalue) {
  return {
    id: 4233,
    fileId: keyvalue[0], // key
    criter: keyvalue[1], // value
    address: '32344'
  }
});

console.log(resultObj);

Is this you are looking for ??

const data = {
    name: 'John Doe',
    company:'Google'
}

console.log(Object.entries(data).map(([fileId,criter])=>({fileId,criter})));

with dummy address and ID :

const data = {
    name: 'John Doe',
    company:'Google'
}

console.log(Object.entries(data).map(([fileId,criter])=>({fileId,criter,id:'1234',address:'1234'})));

Related