3

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.

1

6 Answers 6

8

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)

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

Comments

7

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

Comments

2

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}

1 Comment

map returns a new array. Not fit for this case. A better alternative would be forEach
2

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)

Comments

2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.