如何在不进行硬编码的情况下解决数组问题?

时间:2018-11-09 16:53:56

标签: javascript arrays

如何生产这些物体?

let obs = [
    { car: cars[0], color: colors[0] },
    { car: cars[1], color: colors[1] },
    { car: cars[2], color: colors[2] }
]
从这些数组中

无需进行硬编码

let cars = ["audi", "audi", "audi"]
let colors = ["darkgrey", "red", "silver"]

5 个答案:

答案 0 :(得分:3)

使用Array.map()生成对象数组:

const cars = ["audi", "audi", "audi"]
const colors = ["darkgrey", "red", "silver"]

const result = cars.map((car, i) => ({
  car,
  color: colors[i]
}));

console.log(result);

答案 1 :(得分:1)

通过从每个数组中选择相应的元素,可以将forEach循环与索引和push新对象一起使用:

let cars = ["audi", "audi", "audi"];
let colors = ["darkgrey", "red", "silver"];

let result = [];
cars.forEach((car, i) => {
  result.push({car, color: colors[i]});
});

console.log(result);

答案 2 :(得分:1)

有很多方法可以做到这一点。我个人更喜欢使用数组map函数,它将创建一个新数组。

您可以在任何数组上应用map方法,并使用其索引从另一个数组中检索值

let cars = ["audi", "audi", "audi"]
let colors = ["darkgrey", "red", "silver"];

let result = cars.map((item, index) => {
  return {
    car: item,
    color: colors[index]
  }
});

console.log(result)

您还可以使用常规的for循环,数组forEach和数组reduce

答案 3 :(得分:1)

又花了五分钟,感谢你们:)

let cars = ["audi", "audiXL", "audiRover"]
let colors = ["silver", "darkgrey", "white"]

function matchCars () {   

    let matches = []

    for(let i = 0; i < cars.length; i++) {  
        let object = {car: cars[i], color: colors[i]}
        matches.push(object)
    }
    return matches

}

const answer = matchCars()
console.log(answer);

答案 4 :(得分:0)

这个问题确实是:如何转换structure of arrays to an array of structures

一个简单,通用的解决方案如下:

let aos = soa2aos(
  [ 'car',  ['Civic', 'Integra'] ],
  [ 'year', [1994, 2001] ],
  [ 'color', ['grey', 'orange'] ]
);

console.log(aos);

function soa2aos(...soa) {
  return soa[0].reduce((aos, arr, i) => {
    let o = aos[i] = {};
    soa.forEach(([name, dat]) => o[name] = dat[i]);
    return aos;
  }, []);
}

Read more about Parallel Arrays

我希望这会有所帮助!