简体   繁体   中英

map on javascript object - get the object keys

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.

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

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}

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)

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM