简体   繁体   中英

JavaScript Combine two arrays into one object

I have two arrays, slicesRank and slicesCount with following structure. Each element has id and value, which is an array of 46. values is composed of date and measurement.

eg sliceRank[0] : {id: Catan=rank, values(Array(46)): {date, measurement} }

eg sliceCount[0] : {id: Catan=count, values(Array(46)): {date, measurement} }

What should I do if I want to combine the elements with the same prefix in id names. For example, the first element in this two arrays.

The desired sturcture would be {id: Catan, values(Array(46)): {date, count, rank} }

I tried the following, but the values shows undifined.

    for(i=0; i<slicesRank.length; i++) {
        var newElement = {};
        newElement['id'] = slicesRank[i].id.replace('=rank', '');
        newElement['values'] = {
          date: slicesRank[i].date,
          rank: slicesRank[i].measurement,
          count: slicesCount[i].measurement
        };
        sliceNew.push(newElement);
    };

The structure of slicesRank is like this:

在此处输入图像描述 在此处输入图像描述

By slice I think you mean Array .

const combinedArray = sliceRank.map((sliceItem, itemIndex) => {
    return {
        id,
        values: sliceItem.values.map(({ date, measurement }, valueIndex) => ({
            date,
            count: sliceCount[itemIndex][valueIndex].measurement,
            rank: measurement,
        }))
    }
})

This solution returns an array of objects combined using sliceRank and sliceCount . So now each array item now contains values of structure { date, count, rank } . Array.map is immutable so both slices will be the same.

Here's a sample transformation that you can try:

const combined = slicesRank.map((rank) => {
  const id = rank.id.replace("=rank", "");
  const count = slicesCount.find(
    (count) => count.id.replace("=count", "") === id
  );
  return {
    id,
    values: rank.values.map((val, index) => ({
      date: val.date,
      rank: val.measurement,
      count: count?.values[index].measurement
    }))
  };
});

Here's a working example https://codesandbox.io/s/awesome-lovelace-e31zj?file=/src/index.js

You can try this.

 let sliceRank=[{id: "Catan=rank", values: [{"date":"10/10/2020", "measurement":120} ]}]; let sliceCount=[{id: "Catan=count", values:[{"date":"10/10/2020", "measurement":20} ] }]; let newData=[]; const data = sliceRank.map((slice, sliceIndex) => { return { id:slice.id.split("=")[0], values: slice.values.map(({ date, measurement }, valueIndex) => ({ date, rank: measurement, count: sliceCount[sliceIndex].values.map(r=> r.measurement)[0], })) } }) console.log(data);

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