Laurent Maquet
Laurent Maquet

Reputation: 400

Convert an object into a dictionary of object

I have an object with unknown key/values pairs like that

myObj = {
    key_1: value_1,
    key_2: value_2,
    key_n: value_n
}

I would like to convert it into a dictionary of structured objects like this one:

dictOfStructureObjects =
{
 key_1: {
  name: value_1,
  type: 'foo'},
 key_2: {
  name: value_2,
  type: 'foo'},
 key_n: {
  name: value_n,
  type: 'foo'}
}

I tried this one :

var dic = snapshot.val();
var arr = Object.keys(dic || {});
var names = arr.map(element => {
    var rObj = {};
    rObj[element.value] = {name: dic[element.value], type: 'foo'};
});

But I think that trying to refer to the value of an array element with its property value is not correct...

Upvotes: 6

Views: 28189

Answers (4)

melchoir55
melchoir55

Reputation: 7276

Title is confusing. The op doesn't actually want to convert from a class object to a dictionary. He wants to modify a datastructure.

If you actually want to convert from a class object to a dictionary:

JSON.parse(JSON.stringify(obj))

Upvotes: 1

tiagodws
tiagodws

Reputation: 1395

As pointed out in the comments, your expected output isn't a valid array.

If you want a valid array, you could do it like that:

function convert(obj) {
    return Object.keys(obj).map(key => ({
        name: key,
        value: obj[key],
        type: "foo"
    }));
}

const myObj = {
    key_1: "value_1",
    key_2: "value_2",
    key_3: "value_3",
};

console.log(convert(myObj));

And if you want it as an object, like that:

function convert(obj) {
    return Object.keys(obj).reduce((result, key) => {
        result[key] = {
            name: obj[key],
            type: "foo"
        };
        return result;
    }, {});
}

const myObj = {
    key_1: "value_1",
    key_2: "value_2",
    key_3: "value_3",
};

console.log(convert(myObj));

Upvotes: 10

Nina Scholz
Nina Scholz

Reputation: 386560

You could map the keys as new object with the wanted key and new object.

var object = { key_1: 'value_1', key_2: 'value_2', key_n: 'value_n' },
    newObject = Object.assign(
        ...Object.keys(object).map(k => ({ [k]: { name: object[k], type: 'foo' } }))
    );
    
console.log(newObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

If you want an array...

myObj = {
  key_1: "value1",
  key_2: "value_2",
  key_n: "value_n"
}

var a = [];
Object.entries(myObj).forEach(itm=>a.push({key: itm[0], value: itm[1]}));
console.log(a);

If you want an object

myObj = {
  key_1: "value1",
  key_2: "value_2",
  key_n: "value_n"
}

var a = {};
Object.entries(myObj).forEach(itm=>a[itm[0]] = {key: itm[0], value: itm[1]});
console.log(a);

Upvotes: 2

Related Questions