4

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)',
  }];
3
  • 4
    It is not clear what you mean. Please make a minimal reproducible example Commented Jul 10, 2020 at 8:29
  • Object.entries() will help Commented Jul 10, 2020 at 8:29
  • @mplungjan from two (or more) properties in the object data I'm trying to create new array with new objects. (in this case two objects) Commented Jul 10, 2020 at 8:32

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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'})));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.