javascript - 迭代对象键和值(对象数组)

标签 javascript arrays javascript-objects

我有一个包含键和值的对象(对象数组)

 Obj:{ 
    key1: [{desc:'aaa', pos:0}, {desc:'bbb', pos:1}],
    key2: [{desc:'ccc', pos:0}, {desc:'ggg', pos:1}],
    key3: [{desc:'ddd', pos:0}, {desc:'jjj', pos:1}],
    key4: [{desc:'eee', pos:0}, {desc:'kkk', pos:1}]
  }

从上面...我需要为对象中的每个键获取一个对象数组。所以,我需要获取位置0的desc属性并分配给下面的text1。 text2 和 text 3 将被硬编码。

data = [
  {
    text1: 'aaa',
    text2: 'name2',
    text3: '29/112/2017',
  },
  {
    text1: 'ccc',
    text2: 'name2',
    text3: '29/12/2017',
  },
 {
    text1: 'ddd',
    text2: 'name2',
    text3: '29/12/2017',
  },
 {
    text1: 'eee',
    text2: 'name2',
    text3: '29/12/2017',
  },

]

尝试了以下方法,但不起作用...

 var values = Object.values(obj); - would give me an array of array of objects

 values.map((item, index) => {
    item.map((i, x) => {

    if(i.pos == 0)
        {
           return(
               { 
                  text1: i.desc,
                  text2: 'name2'
                  text3: '29/12/2017'

               }
               )
         }
})

如何获得像“数据”数组这样的结构?

最佳答案

无需使用item.map。您关心的只是 item[0],因此只需直接对其进行索引即可。

var obj = { 
    key1: [{desc:'aaa', pos:0}, {desc:'bbb', pos:1}],
    key2: [{desc:'ccc', pos:0}, {desc:'ggg', pos:1}],
    key3: [{desc:'ddd', pos:0}, {desc:'jjj', pos:1}],
    key4: [{desc:'eee', pos:0}, {desc:'kkk', pos:1}]
  };
  
var values = Object.values(obj);

var result = values.map(item => ({
  text1: item[0].desc,
  text2: 'name2',
  text3: '29/12/2017'
}));

console.log(result);

关于javascript - 迭代对象键和值(对象数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082076/

相关文章:

javascript - 将多个 IF ELSE 语句组合成 AND 语句会导致脚本停止工作

python - numpy 中 1d 到 3d 索引对应的有效算法

javascript - 与标题进行分组/求和

javascript - 更改输入文本中的数字格式

c# - 将 C# Type 转换为 type 数组的类型

javascript - 仅使用位置与跨浏览器使用 window.location 有什么区别吗

javascript - 在 javascript/jquery 中更改基于 xhttp.readyState 的元素文本

javascript - 匿名函数: "object is not a function"

Javascript replace() 仅替换第一个匹配项

javascript - 将对象数组绑定(bind)到其特定的表单字段以进行更新/删除