我有以下两个数组:
array_Two = [colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden");
array_one = ["colorOne", "colorTwo", "colorThree"];
想要这个带有final array =>
的o / pFinalArray = [colorOne:"red",colorTwo:"green",colorThree:"blue"]
我该怎么做?我不知道任何人请知道然后请让我知道。
答案 0 :(得分:2)
假设第一个对象 提供是一个包含键的对象,您可以使用reduce
方法。
array_Two = {colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"};
array_one = ["colorOne", "colorTwo", "colorThree"];
let final = array_one.reduce(function(acc,elem){
acc[elem] = array_Two[elem];
return acc;
},{});
console.log(final);
答案 1 :(得分:2)
使用对象,您可以Object.assign
并使用spread syntax ...
映射单个对象。
var object = { colorZero: "black", colorOne: "red", colorTwo: "green", colorThree: "blue", colorFour: "purple", colorFive: "golden" },
array = ["colorOne", "colorTwo", "colorThree"],
result = Object.assign(...array.map(k => ({ [k]: object[k] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
这样的东西?
var array_Two = {colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"};
var array_one = ["colorOne", "colorTwo", "colorThree"];
var output = {}
array_one.forEach((item) => output[item] = array_Two[item]);
答案 3 :(得分:-1)
看起来这就是你要找的东西:
array_Two = {colorZero:"black", colorOne:"red", colorTwo:"green", colorThree:"blue", colorFour:"purple", colorFive:"golden"};
array_one = ["colorOne", "colorTwo", "colorThree"];
array_one.forEach(element => {
console.log(array_Two[element])
})
在这种情况下,我使用了箭头函数语法,这是一个ES6功能。此外,您应该使用array_Two的大括号