-1

i need to map an object like this

let obj = { 
    a : { value : 5, meta: "sss" },
    b : { value : 1, meta: "rrr" },
    a : { value : 6, meta: "nnn" },
}`

to obtain and object like this

{ a: 5, b: 1, c:6}

I can't get the "key" as a string.

I've tried:

let yyy = Object.keys(obj).map(function (key) {
    return { key: obj[key].value };
});

But it produces an "Array" (while I need an Object) of {key : 5}... with the string "key" instead of the name of the key.

Daan
  • 2,437
  • 16
  • 37
alex
  • 1,304
  • 3
  • 22
  • 50
  • 1
    Does this answer your question? [map function for objects (instead of arrays)](https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays) – Daan Jun 16 '20 at 06:50

6 Answers6

2

You could get the entries and map the key and property value for a new object.

let object = { a : { value: 5, meta: "sss" }, b : { value: 1, meta: "rrr" }, c : { value: 6, meta: "nnn" } },
    result = Object.fromEntries(Object
        .entries(object)
        .map(([key, { value }]) => [key, value])
    );

console.log(result);
Daan
  • 2,437
  • 16
  • 37
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
1

Try this below :

Use Object.keys on your input.

let obj = { 'a': {value: 5, meta: "sss"},
            'b': {value: 1, meta: "rrr"},
            'c': {value: 6, meta: "nnn"},
          };

let output = {};
Object.keys(obj).map(function (item) {
    output[item] = obj[item]['value']
});
console.log(output)


Output : { a: 5, b: 1, c:6}
Abhishek Kulkarni
  • 1,675
  • 1
  • 4
  • 8
  • `map` returns a new array. Not fit for this case. A better alternative would be `forEach` – ABGR Jun 16 '20 at 06:54
0

You could use .reduce

let obj = { 
    a : { value : 5, meta: "sss" },
    b : { value : 1, meta: "rrr" },
    c : { value : 6, meta: "nnn" },
}

var res = Object.keys(obj).reduce((acc, elem)=>{
  acc[elem] = obj[elem].value;
  return acc;
},{});

console.log(res)
ABGR
  • 3,606
  • 1
  • 15
  • 35
0

Try using reduce instead of map..

const obj = { 
    a : { value : 5, meta: "sss" },
    b : { value : 1, meta: "rrr" },
    c : { value : 6, meta: "nnn" },
}


const res = Object.keys(obj).reduce( (res, key) => {
  res[key] = obj[key].value
  return res;
}, {});

console.log(res)
0

You can use reduce function to achieve your result.

let result = Object.keys(obj).reduce((acc,k) => {
    return {
        ...acc,
        [k]:obj[k].value
    };
},{})
console.log(result); // {"a":5,"b":1,"c":6}

I hope it helps.

Farhan Haque
  • 906
  • 1
  • 7
  • 20
0

Using for..of loop and destructuring values

let obj = { 
    a : { value : 5, meta: "sss" },
    b : { value : 1, meta: "rrr" },
    c : { value : 6, meta: "nnn" },
}
const data = Object.entries(obj);
let result={};
for(let [key, {value}] of data) {
  result[key] = value;
}
console.log(result);
khizer
  • 444
  • 5
  • 8