Sen
Sen

Reputation: 773

create new object by value as key in javascript

I would like to create new object with value as key in javascript. I have a obj arrobj, how to create a object having key and value same

function createobj(arrobj){
  var newobj = Object.assign({}, ...arrobj.map(e=>Object.values(e.fields)));
  return newobj
}

var arrobj = [{
  fields: {
   service: "finance",
   country: "SG"
  }
}]


Expected Output
var newobj = {
    finance: "finance",
    SG: "SG"
}

Upvotes: 0

Views: 55

Answers (3)

Luís Ramalho
Luís Ramalho

Reputation: 10208

You can get the values, and then reduce them to a single object with the values as keys:

function createobj(arrobj) {
  return arrobj
    .flatMap((e) => Object.values(e.fields))
    .reduce((p, c) => ((p = { ...p, [c]: c }), p), {});
}

var arrobj = [
  {
    fields: {
      service: "finance",
      country: "SG",
    },
  },
];

console.log(createobj(arrobj));

Upvotes: 1

Francesc Montserrat
Francesc Montserrat

Reputation: 349

This will give you the output you are looking for:

function createobj(arrobj: any): any {
    var newObject = {};
    Object.values(arrobj[0].fields).forEach(v => {
        newObject[v] = v;
    });

    return newObject;
}

Upvotes: 0

odd_wizard
odd_wizard

Reputation: 21

I've changed your mapping function, so the object values get accumulated to one opject that is returned then:

function createobj(arrobj){
  var newobj = Object.assign({}, ...arrobj.map(e => {
    var acc = {};
    for (let value of Object.values(e.fields)) {
      acc[value] = value;
    }
    return acc;
  }));
  return newobj
}


// Test 1
var arrobj = [{
  fields: {
   service: "finance",
   country: "SG"
  }
}]
console.log("Test 1:", createobj(arrobj));

// Test 2
var arrobj2 = [{
  fields: {
   service: "finance",
   country: "SG"
  }
}, {
  fields: {
   service: "finance2",
   country: "SG2"
  }
}]

console.log("Test 2:", createobj(arrobj2));

Upvotes: 0

Related Questions