简体   繁体   English

我有一个数组,我需要使用 javascript 更改数组格式

[英]i have an array and i need to change an array format using javascript

I have an array object,我有一个数组 object,

 const Value = [ {
   "NAME" : "XCODE",
   "XXXCLASS" : [ {
     "V1" : "JOHN",
     "V2" : "MAD"
   },{
     "V1" : "KIRAN",
     "V2" : "TOY"
   } ]
 } ]

I tried it by using forEach method.我通过使用 forEach 方法进行了尝试。 i dont know, its correct way using javascript.我不知道,使用 javascript 的正确方法。

let arry:any = [];
let objVal:any = {};
Value.forEach((value, index) => {
  value.XXXCLASS.forEach( (value, index) =>{
    arry.push(value.V1);
  });
  value.NAME+= ":["+arry+"]";
});

What i mean, dynamically create array with name of "NAME" property with values of "V1" property values.我的意思是,动态创建名称为“NAME”属性的数组,其值为“V1”属性值。 for yours references, kindly check below format.供您参考,请检查以下格式。 I Need to change this below format,我需要更改以下格式,

    const Value = {
      XCODE: ['JOHN','KIRAN']
    };

CODE APPRECIATED.代码赞赏。

You could take the other objects out of the items and map new object with the wanted parts.您可以将其他对象从项目中取出,然后将 map new object 与所需零件一起取出。

 const data = [{ NAME: "XCODE", XXXCLASS: [{ V1: "JOHN", V2: "MAD" }, { V1: "KIRAN", V2: "TOY" }] }], result = data.map(({ NAME, ...o }) => ({ [NAME]: Object.values(o).flatMap(a => a.flatMap(({ V1 }) => V1)) })); console.log(result);

 const values = [ { "NAME": "XCODE", "XXXCLASS": [ { "V1": "JOHN", "V2": "MAD" }], "YYYCLASS": [{ "V1": "KIRAN", "V2": "TOY" } ] } ] const result = values.reduce((map, val) => { let people = map[val.NAME] || []; Object.keys(val).reduce((array, key) => { if (key === 'NAME') { return array; } if (key.includes('CLASS')) { array.push(val[key][0].V1); } return array; }, people); map[val.NAME] = people return map; }, {}); console.log(result);

You can reduce the Value array to an object with NAME s as the properties and an array of V1 names as property values.您可以将Value数组简化为 object,其中NAME作为属性, V1名称数组作为属性值。

 const Value = [ { "NAME": "XCODE", "XXXCLASS": [ { "V1": "JOHN", "V2": "MAD" },{ "V1": "KIRAN", "V2": "TOY" }] }] const result = {} Value.reduce((obj, value) => { obj[value.NAME] = value.XXXCLASS.map(xclass => (xclass.V1)) return obj }, result) console.log(result)

Just one more way to do:还有一种方法:

 const Value = [ { "NAME": "XCODE", "XXXCLASS": [ { "V1": "JOHN", "V2": "MAD" },{ "V1": "KIRAN", "V2": "TOY" } ] } ] var obj = Value[0]; var res = {}; Object.values(obj).map(i=>{ if(typeof i=== "string"){ res[i] = true; }else{ res['XCODE'] = i.map(a=>a.V1) } }) console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM