简体   繁体   中英

Combine Array(s) into single object in JavaScript

Currently I have 3 arrays:

var idArray = [13, 24, 35];    
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];

I would like to merge all the array into one object instead and I tried using for loop but got an error instead:

var finalObj = {};

for (var y = 0; y < dateArray.length; y++) { 
    finalObj[y].id = idArray[y];
    finalObj[y].date =  dateArrayArrange[y];
    finalObj[y].content =  contentArray[y];

}

The end result I want to achieve:

finalObj = [{id:13, date:20181920, content:"content1"},
          {id:24, date:20181120, content:"content2"},
          {id:35, date:20172505, content:"content3"}];

finalObj is an object you need to push the value in an array.Beside you can also use array map method which will return an array so there is no need to separately push the values to an array.

Use map method on any of the arrays and use the index to get the corresponding values from other array

 var idArray = [13, 24, 35]; var dateArray = [20181920, 20181120, 20172505]; var contentArray = ["content1", "content2", "content3"]; let m = idArray.map(function(item, index) { // here the map method will push the object to an // array and will return that array return { id: item, date: dateArray[index], content: contentArray[index] } }) console.log(m) 

Your finalObj is an array of objects, so you must initialise it as an array, like this :

var finalObj = [];
var idArray = [13, 24, 35];
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];

for (var y = 0; y < dateArray.length; y++) {
  finalObj.push(
    { id: idArray[y], date: dateArray[y], content : contentArray[y] }
  )
}

for the "pushing to final array" part, your code inside the loop may work if you add an extra finalObj[y] = {} to initialise it and so you have :

for (var y = 0; y < dateArray.length; y++) {
  finalObj[y] = {}  
  finalObj[y].id = idArray[y];
  finalObj[y].date = dateArray[y];
  finalObj[y].content = contentArray[y];
}

an it works but

  finalObj.push(
    { id: idArray[y], date: dateArray[y], content : contentArray[y] }
  )

is shorter and still readable i think :)

let newObjArray = idArray.map((value, index) => {
        return {
            id: value,
            date: dateArray[index],
            content:contentArray[index]
        }

    });
console.log(newObjArray);

Well, I'm assuming you want an Array Of Objects which has the same length with the idArrays and others.

Here's some code for that:

var finalObjArray = [];

for (var y = 0; y < dateArray.length; y++) { 
    finalObjArray.push({
                       id: idArray[y],
                       date: dateArrayArrange[y],
                       content: contentArray[y]
    });

}

Basically you are adding objects to that array. Hope it helps :)

There isn't a record of finalObj[y] when you set properties, so it return undefined instead.

To fix your problem, create a object with properties then push it to your array.

You can do it like this:

  var idArray = [13, 24, 35]; var dateArray = [20181920, 20181120, 20172505]; var contentArray = ["content1", "content2", "content3"]; var final = []; for (let y = 0; y < idArray.length; y++) { let tmp = {}; tmp.id = idArray[y]; tmp.date = dateArray[y]; tmp.content = contentArray[y]; final.push(tmp); } console.log(final) 

Note: dateArrayArrange does not even exist, I think you mean just dateArray

You need to create objects and add them to the array. This code should work.

var idArray = [13, 24, 35];    
var dateArray = [20181920, 20181120, 20172505];
var contentArray = ["content1", "content2", "content3"];
var finalObj = [];

for (var y = 0; y < dateArray.length; y++) { 
    object = {};
    object.id = idArray[y];
    object.date =  dateArray[y];
    object.content =  contentArray[y];
    finalObj[y] = object;
}

You could collect all key value pairs (for an arbitrary count) in an object and reduce the object while mapping the values.

 var id = [13, 24, 35], date = [20181920, 20181120, 20172505], content = ["content1", "content2", "content3"], result = Object .entries({ id, date, content }) .reduce((r, [k, values]) => values.map((v, i) => ({ ...r[i], [k]: v })), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

by using maps we can write a function which we can extend to any number of arrays and so on. the below function takes a minimum of three distinct fields.

function joinArrays(id, date, content,...array){
    const Arr = [...array];
    const newArr = new Array(Arr.length)
    for(let i=0; i<newArr.length;i++){
        newArr[i] ={}
    }
    Arr.map((rowArr,index)=>{
        rowArr.map((i,k)=>
            {
                key = arguments[index];
                let obj = {};
                obj[key] = i;
                newArr[k]=Object.assign(newArr[k],obj)}
        )
    }
    )
    console.log(newArr);
    return newArr;

}
target = joinArrays('id', 'date', 'content',idArray,dateArray,contentArray);

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