如何在javascript中将数组作为对象传递?

我可以通过这种方式传递数组的值及其工作原理


const obj = [

  { text1: "John", text2: "male" },

  { text1: "Philip", text2: "male" },

  { text1: "Matthew", text2: "male" },

  { text1: "Richard", text2: "male" },

 ];

但我需要这样传递


var obj = {

    text1: ["John", "Philip", "Matthew", "Richard"],

    text2: ["male", "male", "male", "male"]

};


九州编程
浏览 148回答 5
5回答

慕娘9325324

您可能想按键对值进行分组使用forEach循环遍历每个项目input在每个项目中尝试收集属于该项目的所有键的名称使用for...loop每个键的名称并检查是否obj[k]为空,然后我们必须分配一个空数组并将此 key( ) 的值推k入obj[k]。这就是解决方案    const input = [      {text1: 'John', text2: 'male'},      {text1: 'Philip', text2: 'male'},      {text1: 'Matthew', text2: 'male'},      {text1: 'Richard', text2: 'male'},    ];    function toKeyArray(array) {      const obj = {};      array.forEach(item => {        const keys = Object.keys(item);        for (const k of keys) {          (obj[k] = obj[k] || []).push(item[k]);        }      });      return obj;    }    const output = toKeyArray(input);    console.log(output);

炎炎设计

我们可以使用Array.reduce和实现这一点Object.entriesconst obj = [{text1:"John",text2:"male"},{text1:"Philip",text2:"male"},{text1:"Matthew",text2:"male"},{text1:"Richard",text2:"male"},]const formatData = (data) => data.reduce((res, obj) => {  Object.entries(obj).forEach(([key, val]) => {    res[key] = [...(res[key] || []), val];  });  return res;}, {});console.log(formatData(obj));.as-console-wrapper {  max-height: 100% !important;}

慕少森

const input = [  { text1: "John", text2: "male" },  { text1: "Philip", text2: "male" },  { text1: "Matthew", text2: "male" },  { text1: "Richard", text2: "male" }, ];const output = {    text1: input.map( e => e.text1 ),    text2: input.map( e => e.text2 )};

qq_笑_17

const obj = [{    text1: "John",    text2: "male"  },  {    text1: "Philip",    text2: "male"  },  {    text1: "Matthew",    text2: "male"  },  {    text1: "Richard",    text2: "male"  },];var output = {}obj.forEach(item => {  Object.keys(item).forEach(key => {    if (!output[key]) output[key] = [];    output[key].push(item[key])  })})console.log(output);

喵喔喔

使用Array.prototype.reduce,这可以简单地完成。const obj = [  { text1: "John", text2: "male" },  { text1: "Philip", text2: "male" },  { text1: "Matthew", text2: "male" },  { text1: "Richard", text2: "male" },];const output = obj.reduce((acc, cur) => {  Object.keys(cur).forEach((item) => {    acc[item] ? acc[item].push(cur[item]) : acc[item] = [ cur[item] ];  });  return acc;}, {});console.log(output);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript