访问数组内的对象

时间:2019-01-03 07:03:21

标签: javascript angular

我有一个对象,我想将类型的值作为属性访问另一个对象,例如a.Fax,a.Email,a.Call等。但是我在下面写下了一个函数,它将值推入attt。因此,我不想访问ttt,而是要访问ttt中存储的类型(即传真,电子邮件,电话,文本)中的每个值。

export const ActionTypes2 = [
    { value: "OtherLawyer", label: "Other Lawyer", types: ["Fax", "Email", "Call", "Text"] },
    { value: "OtherClerk", label: "Other Clerk", types: ["Fax", "Email", "Call", "Text"]  },
    { value: "BrokerageAgent", label: "Brokerage Agent", types: ["Fax", "Email", "Call", "Text"]  },
    { value: "Lawyer", label: "Lawyer", types: ["Email", "Call", "Text"]  },
    { value: "Clerk", label: "Clerk", types: ["Email", "Call", "Text"] },
    { value: "Client", label: "Client", types: ["Email", "Call", "Text"] },
    { value: "ListingAgent", label: "Listing Agent", types: ["Email", "Call", "Text"] },
    { value: "CooperatingAgent", label: "Cooperating Agent", types: ["Email", "Call", "Text"] }
]


getActionTypes() {
    let t = ActionTypes2;
    let f = <any>{};
    t.map((tt: any) => {
      tt.types.map((ttt: any) => {
        if (!f.ttt) {
          f.ttt = [];
        }
        f.ttt.push(t);
        // console.log(ttt);
      })
    })
    console.log(f);
  }

3 个答案:

答案 0 :(得分:0)

下面怎么样,

getActionTypes() {
   let t = ActionTypes2;
   let f = <any>{};
   t.map((tt: any) => {
     if (!f.ttt) {
       f.ttt = [];
     }
     f.ttt.push(tt.types);
   })
   console.log(f.ttt);  }

答案 1 :(得分:0)

您应按如下所示将f.ttt替换为f [ttt]

getActionTypes() {
    let t = ActionTypes2;
    let f = <any>{};
    t.map((tt: any) => {
        tt.types.map((ttt: any) => {
            if (!f[ttt]) {
                f[ttt] = [];
            }
            f[ttt].push(t);
            // console.log(ttt);
        })
    })
    console.log(f);
}

答案 2 :(得分:0)

您可以将数组here {{}}放置到一个对象上(请注意,SO打印控制台有些奇怪,请按F12键并查看控制台以获取实际结果):

const data = [{"value":"OtherLawyer","label":"Other Lawyer","types":["Fax","Email","Call","Text"]},{"value":"OtherClerk","label":"Other Clerk","types":["Fax","Email","Call","Text"]},{"value":"BrokerageAgent","label":"Brokerage Agent","types":["Fax","Email","Call","Text"]},{"value":"Lawyer","label":"Lawyer","types":["Email","Call","Text"]},{"value":"Clerk","label":"Clerk","types":["Email","Call","Text"]},{"value":"Client","label":"Client","types":["Email","Call","Text"]},{"value":"ListingAgent","label":"Listing Agent","types":["Email","Call","Text"]},{"value":"CooperatingAgent","label":"Cooperating Agent","types":["Email","Call","Text"]}];

const groupByType = (data) =>
  data.reduce(
    (result, { types, ...rest }) =>
      types.reduce((result, type) => {
        result[type] = result[type] || [];
        result[type].push(rest);
        return result;
      }, result),
    {},
  );
console.log(groupByType(data));

reduce用于将'T数组转换为'U数组,甚至产生相同类型但翻倍的新数组(例如[1,2,3].map(x=>x*2))。传递给map的函数应该是纯函数,因此它不应使用或变异该函数外部定义的内容或更改要映射的数组。