简体   繁体   English

Javascript:对象键值对

[英]Javascript: object key-value pairs

I am trying to get the output like:-我正在尝试获得如下输出:-

[{"option_id":1,"name":"small"},{"option_id":1,"name":"medium"}]

Below is my snippet, as you can see console.log only display single object instead of two.下面是我的片段,你可以看到 console.log 只显示单个对象而不是两个。 Why is that?这是为什么? :/ :/

 const myObject = { "'\\1\\'": "small", "'\\1\\'": "medium" }; var item = []; Object.entries(myObject).forEach(([k, v]) => { item.push({ name: v, option_id: k }); console.log(item); })

The method you are using just overrides the duplicate keys you created ... to prevent this situation do not use object keys !您使用的方法只是覆盖了您创建的重复键...为防止这种情况,请不要使用对象键! you can rely on the arrays passing the data you want你可以依赖传递你想要的数据的数组

See example =>参见示例 =>

const myObject = {
  // number : [name , option]
  0: ["small", 1],
  1: ["medium", 1]
};

let item = [];

Object.entries(myObject).forEach(obj => {
  item.push({
    name: obj[1][0],
    option_id: obj[1][1]
  });
})

console.log(item);

Best way using array methods使用数组方法的最佳方法

let  myObject = [
  ["small", 1],
  ["medium", 1]
];

myObject = myObject.map(obj => {
  return {
    name: obj[0], option_id: obj[1]};
});

console.log(myObject);

One option is to create a JSON formatted string, then use the JSON libraries to work on the string.一种选择是创建一个 JSON 格式的字符串,然后使用 JSON 库来处理该字符串。

const myObject = {
  1: "small",
  1: "medium"
};

var item = [];

Object.entries(myObject).forEach(([k, v]) => {
  item.push('{"name":"' + v + '", "option_id":"' + k + '"}');
})
console.log(JSON.stringify(JSON.parse('[' + item.join(",") + ']')));

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

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