Home > Net >  creating json value pair?
creating json value pair?

Time:07-19

i have 2 arrays of same length

var arr1= ["1", "2", "3", "4", "5", "6", "7", "8"]
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"]

i want output like

result = [{id:1,chan:discovery},{id:2,chan:nationalgeographic},{id:3,chan:hbo},{id:4,chan:wb},{id:5,chan:comedycentral},{id:6,chan:pogo},{id:7,chan:cnn},{id:8,chan:romedynow}]

somebody please share your ideas.

CodePudding user response:

Use map for that:

const newArr = arr1.map((item, index) => ({ id: item, chan: arr2[index] }));

CodePudding user response:

var arr1= ["1", "2", "3", "4", "5", "6", "7", "8"];
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"];

let result = [];
for(let i = 0; i < arr1.length; i  ) {
    let obj = {
    id: arr1[i],
    chan: arr2[i]
  }
  result.push(obj);
}

console.log(result);

CodePudding user response:

I think you're looking for something like this.

var arr1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"]

var result = []

for (var i = 0; i < arr1.length; i  ) {
    result.push({"id": arr1[i], "chan": arr2[i]})
}

console.log(result)

And the result I'm getting is

[ { id: '1', chan: 'discovery' },
  { id: '2', chan: 'nationalgeographic' },
  { id: '3', chan: 'hbo' },
  { id: '4', chan: 'wb' },
  { id: '5', chan: 'comedycentral' },
  { id: '6', chan: 'pogo' },
  { id: '7', chan: 'cnn' },
  { id: '8', chan: 'romedynow' } ]

Good luck!

  • Related