1

Is there a built-in lodash function to take this:

let params = ['foo', 'bar', 'baz', 'zle'];
let newArray = [];

params.forEach((element, index) => {
  let key = "name" + index;
  newArray.push({ key: element })
});

console.log(newArray);

And expected output should be like this:

var object = {
  a: {
    name1: "foo",
    name2: "bar",
  },
  b: {
    name1: "baz",
    name2: "zle",
  }
}
3
  • 2
    What is the delimiter for a and b in output. i.e what is the deciding on where to break the array params. You can simply use Object.assign() to convert Array to object, But output on params will be single dimension object. Refer this stackoverflow.com/questions/4215737/convert-array-to-object Commented Aug 22, 2019 at 6:29
  • Do you want an array of objects or a nested object as output? Are the keys consecutive alphabets or are a and b dummy keys? Commented Aug 22, 2019 at 6:33
  • Your code suggests you want an array in newArray, but then in your expected output you show a nested object. Commented Aug 22, 2019 at 6:54

3 Answers 3

2

May this help you. I know that you should provide more information that what do really want to implement. but i got an idea that might help you.

let params = ['foo', 'bar', 'baz', 'zle'];
const keys = ['a', 'b', 'c', 'd']

let data = {}

while(params.length){

  const [a, b] = params.splice(0, 2) 
  const key = keys.splice(0, 1)

  data[key] = {
      name1: a,
      name2: b,
    }

}

console.log(data)

output will be:

{
  a: {
    name1: "foo",
    name2: "bar",
  },
  b: {
    name1: "baz",
    name2: "zle",
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I got the solution.
1

You can convert your array into Json like format that can be done like this

var jsonObj = {};
for (var i = 0 ; i < sampleArray.length; i++) {
jsonObj["position" + (i+1)] = sampleArray[i];
 }

Comments

1

I have solved the issue. Solution for this issue is

 let colLength = 4;

 let breakableArray = _.chunk(data, 4);

  breakableArray.forEach((arrayObject,key)=>{
    let object = new Object();
    for(let i = 0; i < colLength; i++) {
      object[i] = arrayObject[i] != undefined ? arrayObject[i] : "-";
    }  
    finalObject[key] = object;
  })  

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.