将JSON数组推送到数组的键值对中

时间:2019-04-23 16:17:30

标签: javascript

我有一个如下的JSON数组:

rows =[
        {
            "ID":132,
            "TITLE":"Questions one",
            "DESCRIPTION":"Questions one DESCRIPTION",
            "EXPERT_RATING":3,
            "DURATION":15,
            "SOURCE_URL":"http://testing.com",
            "COMMENT":null,
            "UserID": 1214
        },
        {
            "ID":137,
            "TITLE":"Questions two",
            "DESCRIPTION":"Questions two description",
            "EXPERT_RATING":3,
            "DURATION":15,
            "SOURCE_URL":"http://question2.com",
            "COMMENT":null,
            "UserID": 1214
        }
    ]

现在,我想将其推送到数组中,因此它应如下所示:

res[132] = ['Questions one', 'Questions one DESCRIPTION', 3, 15, 'http://testing.com', null, 1214]
res[137] = ['Questions two', 'Questions two DESCRIPTION', 3, 15, 'http://question2.co', null,1214]

我尝试了以下鳕鱼,但显示了很多空记录

rows.forEach(function(key){

                recJson[key.ID] = [key.TITLE, key.DESCRIPTION, key.EXPERT_RATING, key.DURATION, key.SOURCE_URL, key.COACHING_TIPS, key.MGR_COMMENT, key.UserID]             
            });

console.log(recJson);

告诉我我做错了吗?

5 个答案:

答案 0 :(得分:2)

如果直接使用该代码,则表示不一致或错字。您的数据集似乎在TITLE和RTITLE之间互换。如果您的数据确实如此,则可以使用reduce函数和Object.values随意将每个条目的所有值推入数组:

rows.reduce((acc, curr) => {
  acc[curr["ID"]] = Object.values(curr);
  return acc;
}, {})

这将导致以下结果:

{
  132: [132, "Questions one", "Questions one DESCRIPTION", 3, 15, "http://testing.com", null]
  137: (7) [137, "Questions two", "Questions two description", 3, 15, "http://question2.com", null]
}

这应该给您您想要的东西。

答案 1 :(得分:1)

这是我的方法。

var rows = [{
		"ID": 132,
		"TITLE": "Questions one",
		"DESCRIPTION": "Questions one DESCRIPTION",
		"EXPERT_RATING": 3,
		"DURATION": 15,
		"SOURCE_URL": "http://testing.com",
		"COMMENT": null
	},
	{
		"ID": 137,
		"RTITLE": "Questions two",
		"DESCRIPTION": "Questions two description",
		"EXPERT_RATING": 3,
		"DURATION": 15,
		"SOURCE_URL": "http://question2.com",
		"COMMENT": null
	},
	{
		"ID": 137,
		"RTITLE": "Questions three",
		"DESCRIPTION": "Questions three description",
		"EXPERT_RATING": 3,
		"DURATION": 15,
		"SOURCE_URL": "http://question3.com",
		"COMMENT": null
	},
	{
		"ID": 137,
		"RTITLE": "Questions four",
		"DESCRIPTION": "Questions four description",
		"EXPERT_RATING": 3,
		"DURATION": 15,
		"SOURCE_URL": "http://question4.com",
		"COMMENT": null
	}
];
var arr = rows.map(ar => Object.values(ar));
var obj = {};
arr.map(ar => {
	var id = ar[0];
	ar.splice(0, 1);
	//if duplicate key occures creating a nested array.
	if (obj.hasOwnProperty(id)) {
		if (Array.isArray(obj[id][0])) {
			obj[id].push(ar);
		} else {
			obj[id] = [obj[id], ar];
		}
	} else {
		obj[id] = ar;
	}
});

console.log(obj);

已编辑

已针对重复的键出现进行了更新。

答案 2 :(得分:0)

代码中缺少的是:

var recJson = [];

这意味着您要通过索引将它们添加到 数组,因此,为了使javascript要添加索引132,它必须添加索引0 -{131首先-这样您会得到很多null / undefineds。

您可以将每个条目推入数组,但这不能让您按ID访问它们-因此最好使用对象

var recJson = {};

这会将您的值添加为属性。

rows = [{
    "ID": 132,
    "TITLE": "Questions one",
    "DESCRIPTION": "Questions one DESCRIPTION",
    "EXPERT_RATING": 3,
    "DURATION": 15,
    "SOURCE_URL": "http://testing.com",
    "COMMENT": null
  },
  {
    "ID": 137,
    "RTITLE": "Questions two",
    "DESCRIPTION": "Questions two description",
    "EXPERT_RATING": 3,
    "DURATION": 15,
    "SOURCE_URL": "http://question2.com",
    "COMMENT": null
  }
]


var recJson = {};
rows.forEach(function(key) {
  recJson[key.ID] = [key.RTITLE, key.DESCRIPTION, key.EXPERT_RATING, key.DURATION, key.SOURCE_URL, key.COACHING_TIPS, key.MGR_COMMENT, key.ATTUID];
});

console.log(recJson);

答案 3 :(得分:0)

  • 首先,您需要确保数组的大小适合那些索引。
  • 接下来,您需要某种方式来获取字段的顺序。 (确保您的字段名称一致)
  • 最后,只需减少每一行的字段即可获取适当的值。

let rows = [{
  "ID": 132,
  "TITLE": "Questions one",
  "DESCRIPTION": "Questions one DESCRIPTION",
  "EXPERT_RATING": 3,
  "DURATION": 15,
  "SOURCE_URL": "http://testing.com",
  "COMMENT": null
}, {
  "ID": 137,
  "RTITLE": "Questions two",
  "DESCRIPTION": "Questions two description",
  "EXPERT_RATING": 3,
  "DURATION": 15,
  "SOURCE_URL": "http://question2.com",
  "COMMENT": null
}];

let res = new Array(138);
let fields = [ 'RTITLE', 'DESCRIPTION', 'EXPERT_RATING', 'DURATION', 'SOURCE_URL', 'COMMENT' ];

rows.forEach(row => {
  res[row.ID] = fields.reduce((arr, field) => arr.concat(row[field]), []);
});

console.log(res);
.as-console-wrapper { top: 0; max-height: 100% !important; }

正如其他人所建议的那样,也许一个对象会更好。

rows.reduce((obj, row) => {
  return Object.assign(obj, { [row.ID] : fields.reduce((arr, field) => {
    return arr.concat(row[field]);
  }, []) })
}, res);

let rows = [{
  "ID": 132,
  "TITLE": "Questions one",
  "DESCRIPTION": "Questions one DESCRIPTION",
  "EXPERT_RATING": 3,
  "DURATION": 15,
  "SOURCE_URL": "http://testing.com",
  "COMMENT": null
}, {
  "ID": 137,
  "RTITLE": "Questions two",
  "DESCRIPTION": "Questions two description",
  "EXPERT_RATING": 3,
  "DURATION": 15,
  "SOURCE_URL": "http://question2.com",
  "COMMENT": null
}];

let res = {};
let fields = [ 'RTITLE', 'DESCRIPTION', 'EXPERT_RATING', 'DURATION', 'SOURCE_URL', 'COMMENT' ];

rows.reduce((obj, row) => Object.assign(obj, { [row.ID] : fields.reduce((arr, field) => arr.concat(row[field]), []) }), res);

console.log(res);
.as-console-wrapper { top: 0; max-height: 100% !important; }

答案 4 :(得分:0)

如果您能够使用它,我建议在这种情况下使用Map()来保存您的新结构。创建一个array with holes is not a good idea。或者,您可以使用一个对象,其中ngrok http -host-header=rewrite localhost:9292 keys,而ids是所需的数组。

这将是values解决方案:

Map
const rows = [
  {
    "ID":132,
    "TITLE":"Questions one",
    "DESCRIPTION":"Questions one DESCRIPTION",
    "EXPERT_RATING":3,
    "DURATION":15,
    "SOURCE_URL":"http://testing.com",
    "COMMENT":null
  },
  {
    "ID":137,
    "RTITLE":"Questions two",
    "DESCRIPTION":"Questions two description",
    "EXPERT_RATING":3,
    "DURATION":15,
    "SOURCE_URL":"http://question2.com",
    "COMMENT":null
   }
];

let myMap = rows.reduce((acc, o) =>
{
    acc.set(o.ID, [
        o.hasOwnProperty("TITLE") ? o.TITLE : o.RTITLE,
        o.DESCRIPTION,
        o.EXPERT_RATING,
        o.DURATION,
        o.SOURCE_URL,
        o.COMMENT
    ]);
    return acc;
}, new Map());

console.log("Data for id 132:", myMap.get(132));
console.log("Data for id 137:", myMap.get(137));

请注意,确保结果数组按需要排序的唯一方法是按所需顺序枚举所有属性。您不能相信.as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;}会为您提供具有相同键顺序的所有数组。阅读here