0

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"
}

2
  • 2
    And the problem is? Commented Apr 24, 2020 at 11:00
  • var arrobj = [ fields: { - something is not right. Commented Apr 24, 2020 at 11:02

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

good one, though I wonder if shadowing values fn in local scope is the best example, if someone take the line out it would not run and might be hard to track why
What do you mean exactly @VitaliyTerziev? There's no values variable in any parent scope... but yes, it can be better to just chain the reduce
Ok, maybe I am missing something then - I can call 'values' in the global scope and there is such fn, if you strip the code from the 'createobj' fn it would not work (previous version). Yep chaining looks better indeed.
You're right! I'm the one missing something, wasn't aware of the global values function :)
fyi - I checked node, then FF and both were missing this fn so I guess it is just debugger helper fn (at least in FF) I wasn't able to find any ref in docs as well .. the code was just fine after all.. :)
0

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.