0

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",
  }
}
adiga
  • 34,372
  • 9
  • 61
  • 83
Priya
  • 88
  • 9
  • 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 https://stackoverflow.com/questions/4215737/convert-array-to-object – Abhinav Kulshreshtha Aug 22 '19 at 06: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? – adiga Aug 22 '19 at 06:33
  • Your code suggests you want an array in newArray, but then in your expected output you show a nested object. – connexo Aug 22 '19 at 06:54

3 Answers3

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",
  }
}
Bob White
  • 733
  • 5
  • 20
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;
  })  
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
Priya
  • 88
  • 9
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];
 }