测试一些基本的JavaScript代码时出现意外输出

时间:2019-05-12 02:55:44

标签: javascript arrays object ecmascript-6

我正在学习Javascript中的不同数组函数,并且无法理解为测试array.map()编写的基本代码的输出。

$ for i in testsort_{1..3}.csv; do printf "\n%s\n" $i; cat $i; done

testsort_1.csv
WH_01,TRAINAMS,A10,1221-ESD
WH_01,TRAINAMS,A10,PWR-120
WH_01,TRAINAMS,A101,PWR-120

testsort_2.csv
WH_02,TRAINCLE,A1,074-HD-SATA
WH_02,TRAINCLE,A15,102-55665

testsort_3.csv
WH_03,TRAINLON,L10A3,3005-20
WH_03,TRAINLON,L10A3,3005-21
WH_03,TRAINLON,UK-B3,101859

预期产量

let contacts = [{
  "firstName": "Jim",
  "lastName": "Smith"
}, {
  "firstName": "Laura",
  "lastName": "Bush"
}, {
  "firstName": "Adam",
  "lastName": "Shaw"
}];

let tempJson = {};

const newContacts = contacts.map(contact => {
//tempJson = {}
tempJson[contact.firstName] = contact.lastName
console.log(tempJson);
return tempJson;
});

console.log(newContacts);

实际输出

//tempJson
{ "Jim": "Smith" }
{ "Jim": "Smith", "Laura": "Bush" }
{ "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" }

//newContacts
[ { "Jim": "Smith", }, 
  { "Jim": "Smith", "Laura": "Bush"}, 
  { "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" } ]

新的contacts数组不是仅由map函数返回的对象组成吗?

我正在丢失某些东西,我不确定它是什么。

3 个答案:

答案 0 :(得分:0)

您将返回对tempJson的引用,因此您在tempJson中的最终结果会反映在newContacts中,而不是clone您的tempJson中,然后返回克隆的对象。

let contacts = [{
    "firstName": "Jim",
    "lastName": "Smith"
  }, {
    "firstName": "Laura",
    "lastName": "Bush"
  }, {
    "firstName": "Adam",
    "lastName": "Shaw"
  }];
  
  let tempJson = {};
  
  const newContacts = contacts.map(contact => {
    let clonedObj = {};
    tempJson[contact.firstName] = contact.lastName
    Object.assign(clonedObj, tempJson);
    return clonedObj;
  });
  
  console.log(newContacts);

PS:reduce更适合其他人指出。

let contacts = [{
    "firstName": "Jim",
    "lastName": "Smith"
  }, {
    "firstName": "Laura",
    "lastName": "Bush"
  }, {
    "firstName": "Adam",
    "lastName": "Shaw"
  }];
  

const output = contacts.reduce((accu, {firstName, lastName}, i) => {
    accu.push({...accu[i-1], [firstName]: lastName });
    return accu;
}, []);

console.log(output);

答案 1 :(得分:0)

.map()函数旨在用于获取数组并将每个元素转换为新数组的相应元素值。看来您想要做的是从数组的元素中构建一个新的 object ,因此对于.map()来说,这并不是真正的工作。更通用的.reduce()函数会更好:它允许您在迭代遍历数组元素时将结果累积为任何类型的值。

在这种情况下,您可以按以下方式使用.reduce()

const newContacts = contacts.reduce(function(result, contact) {
  result[contact.firstName] = contact.lastName;
  return result;
}, {});

{}的第二个参数.reduce()是起始值。每次迭代时,它都会作为第一个参数传递给回调函数,并且回调函数负责返回更新后的值。

答案 2 :(得分:0)

改为使用reduce

let contacts = [{
  "firstName": "Jim",
  "lastName": "Smith"
}, {
  "firstName": "Laura",
  "lastName": "Bush"
}, {
  "firstName": "Adam",
  "lastName": "Shaw"
}];

const newContacts = Object.entries(contacts.reduce((acc, { firstName, lastName }) => {
  acc[firstName] = lastName;
  return acc;
}, {})).map(([k, v]) => ({[k]: v}));

console.log(newContacts);