0

I've been having trouble to get this function to work with multiple properties and values.

the code here works fine as long as the object contains one property and value.

var arr = [ [{ prop: 'val1' }], [{ prop: 'val2' }], [{ prop: 'val3' }] ]

var res = arr.map(getObject);

function getObject(o) {
    return Array.isArray(o) ?  getObject(o[0]) : o;
}
console.log(res);


[
    {
      "prop": "val1"
    },
    {
      "prop": "val2"
    },
    {
      "prop": "val3"
    }
  ]

  • I'm trying to get the function to work so that it can log an object with multiple properties and values

ex.

    oldArray = [ [{ prop1: 'val1', prop2: 'val2' }], [{ prop1: 'val1', prop2: 'val2' }], [{ prop1: 'val1', prop2: 'val2' }] ];


    newArray = [
    {
      "prop1": "val1",
      "prop2": "val2",
    },
    {
      "prop1": "val1",
      "prop2": "val2",
    },
    {
      "prop1": "val1",
      "prop2": "val2",
    },
  ];
1
  • You dont have to do anything, you can just do console.log(newArray). What is exactly the problem? Commented Feb 11, 2020 at 9:41

1 Answer 1

1

var oldArray = [ [{ prop1: 'val1', prop2: 'val2' }, { prop11: 'val11', prop22: 'val22' }], [{ prop1: 'val1', prop2: 'val2' }], [{ prop1: 'val1', prop2: 'val2' }] ];

var newArray = [];
oldArray.map(function(subArray){
    subArray.map(function(prop){
        newArray.push(prop);
    });
});

console.log('oldArray', oldArray)
console.log('newArray', newArray)

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

1 Comment

Thank you so much! you saved me a lot of time. code works perfectly!

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.