Javascript 将两个数组合并到一个记录数组中
我目前正在尝试将数组连接到一个记录数组中,其中两个值直接排列如下: 分数:Javascript 将两个数组合并到一个记录数组中,javascript,arrays,sorting,records,Javascript,Arrays,Sorting,Records,我目前正在尝试将数组连接到一个记录数组中,其中两个值直接排列如下: 分数: [1,0,43,12] 食物: 我想创建一个这样的数组: [{food: 'ham', score: 1}, {food: 'cheese', score: 0}, {food: 'potato', score: 43}, {food: 'cabbage', score: 12}] 我可以创建个人记录: {food: 'ham', score: 1} {food: 'cheese', score: 0} 等等 使用
[1,0,43,12]
食物:
我想创建一个这样的数组:
[{food: 'ham', score: 1}, {food: 'cheese', score: 0}, {food: 'potato', score: 43}, {food: 'cabbage', score: 12}]
我可以创建个人记录:
{food: 'ham', score: 1}
{food: 'cheese', score: 0}
等等
使用此代码:
var foodscore = []
for(i in score){
var record = {}
record.food = food[i]
record.score = score[i]
foodscore.push(record)
}
但是,当我使用console.log(foodscore)时,我得到:
返回,而不是记录。解决这个问题的好办法是什么
编辑:我忘了添加这段代码是函数的一部分,我想将上面连接的数组的值返回到函数的值。如何以完整形式返回数组,而不输出[Object,Object,Object,Object]?如果数组的长度始终相同,并且两个数组(分数和食物)的值顺序相同,则可以迭代其中一个数组并按如下方式创建对象:
var score = [1,0,43,12], food = ['ham','cheese','potato','cabbage'], result = [];
for (var i = 0; i < score.length; i++) {
result.push({'food': food[i], 'score': score[i]});
}
console.log(result);
var得分=[1,0,43,12],食物=['火腿','奶酪','土豆','卷心菜'],结果=[];
对于(变量i=0;i
如果两个阵列的长度相同,您可以采用如下方法:
// We define a constructor function that
// will be used for the creation of the objects that we will push to our
// array
function FoodScore(food, score){
this.food = food;
this.score = score;
}
// The array with the food scores.
var foodScores = [];
// We loop through the scores array and for each element
// we create a food score object and we push it to the foodScores.
for(var i=0, len=score.length; i<len; i++){
foodScores.push(new FoodScore(food[i], score[i]));
}
//我们定义了一个构造函数
//将用于创建对象,我们将推送到
//排列
功能食品核心(食品、分数){
这就是食物;
这个分数=分数;
}
//食物得分的数组。
var foodScores=[];
//我们循环遍历分数数组,并对每个元素进行排序
//我们创建一个food score对象并将其推送到FoodScore。
对于(var i=0,len=score.length;i您的代码应该会生成所需的结果。看起来您只是在打印结果时遇到了问题
尝试此操作以查看阵列实际包含的内容:
console.dir(foodscore);
但是,为了更简洁地生成数组,您可以使用:
var foodscore = score.map(function (sc, i) {
return { score: sc, food: food[i] };
});
您的代码很好,但您误解了console.log
和console.dir
之间的区别
.log()
只是调用Object
的toString
方法。这就是为什么会看到一个字符串,它显示了数组的粗略描述
.dir()
而是输出指定JavaScript对象属性的交互式列表
您的代码应该是:
//This will return an array/object where everything in it can be examined
console.dir( foodscore );
您如何检查是否返回了预期结果?您是否检查了对象
是否具有所需的属性?这很好,但是我顶部的代码在函数中,当我返回数组值时,仍然返回[Object]。这是为什么?
var foodscore = score.map(function (sc, i) {
return { score: sc, food: food[i] };
});
//This will return an array/object where everything in it can be examined
console.dir( foodscore );