如何返回对象中的属性并使它们有序?

时间:2019-10-12 20:25:16

标签: javascript arrays

给出以下两个数组:

var amounts = [9, 1, 8, 16, 5, 1, 42]
var animals = ["ducks", "elephants", "pangolins", "zebras", "giraffes", "penguins", "llamas"]

我必须编写一个接受两个变量并返回组合字符串的函数。预期的输出是:

"9 ducks 1 elephants 8 pangolins 16 zebras 5 giraffes 1 penguins 42 llamas"

我创建了一个类似于预期字符串的对象。现在,我需要按此顺序打印属性。

function animalsAmounts(arr1, arr2){
    let object = {};
    arr2.forEach((arr2, i) => object[arr2] = arr1[i]);
    return object
    let result = Object.keys(object).map(function(key) {
        return [Number(key), obj[key]];
    }); return result
}

console.log(animalsAmounts(amounts, animals))

它打印:

{ ducks: 9,
  elephants: 1,
  pangolins: 8,
  zebras: 16,
  giraffes: 5,
  penguins: 1,
  llamas: 42 }

我不知道如何以字符串形式返回预期结果。我尝试了各种方法来记录数量和动物,但是设法只返回了其中一个。

2 个答案:

答案 0 :(得分:3)

Array.prototype.join()从将它们与您选择的内容连接起来的数组项中创建一个字符串。

animals.map((a, i) => `${amounts[i]} ${a}`).join(" ")

var amounts = [9, 1, 8, 16, 5, 1, 42]
var animals = ["ducks", "elephants", "pangolins", "zebras", "giraffes", "penguins", "llamas"]

console.log(animals.map((a, i) => `${amounts[i]} ${a}`).join(" "))

答案 1 :(得分:0)

您可以采用动态方法来对同一索引处的数组和映射值进行任意计数,然后再连接到单个字符串。

var amounts = [9, 1, 8, 16, 5, 1, 42]
var animals = ["ducks", "elephants", "pangolins", "zebras", "giraffes", "penguins", "llamas"],
    result = [amounts, animals]
        .reduce((r, a) => a.map((v, i) => (r[i] ? r[i] + ' ' : '') + v), [])
        .join(' ');

console.log(result);