Hari Krishnan
Hari Krishnan

Reputation: 93

i have an array and i need to change an array format using javascript

I have an array object,

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

I tried it by using forEach method. i dont know, its correct way using 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. for yours references, kindly check below format. I Need to change this below format,

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

CODE APPRECIATED.

Upvotes: 0

Views: 643

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386540

You could take the other objects out of the items and map new object with the wanted parts.

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);

Upvotes: 1

ABGR
ABGR

Reputation: 5205

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)

Upvotes: 1

AJ_
AJ_

Reputation: 1485

You can reduce the Value array to an object with NAMEs as the properties and an array of V1 names as property values.

 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)

Upvotes: 1

AngelSalazar
AngelSalazar

Reputation: 3113

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);

Upvotes: 1

Related Questions