简体   繁体   中英

How to map an array to object

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",
  }
}

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",
  }
}

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

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];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM