简体   繁体   English

map 上 javascript object - 获取 object 密钥

[英]map on javascript object - get the object keys

i need to map an object like this我需要像这样的 map 和 object

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

to obtain and object like this像这样获得和 object

{ 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.但它会产生一个{key: 5}...的“数组”(而我需要一个对象)......使用字符串“key”而不是键的名称。

You could get the entries and map the key and property value for a new object.您可以获得新 object 的条目和 map 的键和属性value

 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.在您的输入中使用 Object.keys。

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你可以使用.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..尝试使用 reduce 而不是 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.您可以使用reduce function 来实现您的结果。

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使用for..of循环和解构值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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