简体   繁体   English

如何在JavaScript中对两个对象和数组进行映射

[英]How to do mapping for two objects and array in javascript

I have such a object and array which I received response from my server. 我有一个这样的对象和数组,我从服务器收到了响应。 I need to convert that to second format at below in order to print the value in the website. 我需要在下面将其转换为第二种格式,以便在网站上打印该值。 Is this something need to do object mapping? 这需要做对象映射吗? or parse JSON or please kindly help. 或解析JSON或请提供帮助。

{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]} , {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}

Convert from Above to below 从上转换为下

'{"SEOUL" : "38", "BUSAN" : "CAPITAL", "NAMPODONG" : "M31"}'

var finalObj = {};
response.header.forEach(function(item, index) {
finalObj[item] = response.data[0][index];
});

Above code is working fine as it create variable and loop for header and get its value and printed in html. 上面的代码可以正常工作,因为它创建变量并为标头循环并获取其值并以html打印。 the header and data are from the server so when I enter something let say "A" then it will look for SEOUL header then print 38 in html as tables are looks below. 标头和数据来自服务器,因此当我输入一些内容时,说“ A”,它将查找SEOUL标头,然后在HTML中打印38,如下表所示。

key value : A 键值:A

header : SEOUL BUSAN NAMPODONG 标头:首尔釜山楠榜

data : 38 CAPITAL M31 数据:38 CAPITAL M31

I do have a lot of data in the database, above is just an example. 我的数据库中确实有很多数据,上面只是一个例子。 So let say I enter B then the B is not in database so I want to see the value "No found" in html but this code printing nothing so not sure whether it was proceed or not. 因此,可以说我输入了B,然后B不在数据库中,所以我想在html中看到值“ No found”,但是此代码未打印任何内容,因此不确定是否继续。

Create a variable & loop over the object.header to get each key and object.data[0] to get its value object.header上创建一个变量并循环,以获取每个键,并在object.data[0]中获取其值

 var myObj = { "header": ["SEOUL", "BUSAN", "NAMPODONG"], "data": [ [38, "CAPITAL", "M31"] ] } var tempObj = {}; myObj.header.forEach(function(item, index) { tempObj[item] = myObj.data[0][index] }) console.log(tempObj) 

As you received it from server – I assume that it is JSON string. 当您从服务器收到它时–我假设它是JSON字符串。

Basically you have two arrays here that you want to reduce to an object. 基本上,这里有两个要简化为对象的数组。 So I would do it like this: 所以我会这样:

 const object = JSON.parse('{"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]}'); const result = object.header.reduce(function(accumulator, element, i){ accumulator[element] = object.data[0][i] // You had nested array here so I have to get first element. return accumulator; }, {}); console.log(result); 

I assumed that nested array for data attribute is some kind of formatting mistake. 我认为data属性的嵌套数组是某种格式错误。 If it's not – you have to map though it's elements first and only then reduce. 如果不是,则必须先映射元素,然后才缩小。

You can use zipObj from Ramda library. 您可以使用Ramda库中的zipObj

The code would look like this: 代码如下所示:

 const res = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"]]} const obj = R.zipObj(res.header, res.data[0]) console.log(obj) 
 <script src="//cdn.jsdelivr.net/npm/ramda@latest/dist/ramda.min.js"></script> 

You could map the new objects with the wanted keys. 您可以使用所需键映射新对象。

The result is an array with objects, because your data is a nested array with actually only one array. 结果是一个带有对象的数组,因为您的数据是一个嵌套的数组,实际上只有一个数组。 But it looks like taht data could contain more than one row. 但是,看起来这些数据可能包含多个行。

 var data = { header: ["SEOUL", "BUSAN", "NAMPODONG"], data: [[38, "CAPITAL", "M31"]] }, result = data.data.map(a => Object.assign(...data.header.map((k, i) => ({ [k]: a[i] })))); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can map the data array of arrays into another array of object using as keys the strings in header array: 您可以使用header数组中的字符串作为键将数组的data数组映射到另一个对象数组:

 function transform(obj) { return obj.data.map(function(subArray) { // for each subArray in the data array return subArray.reduce(function(o, val, i) { // create a new object o which... o[ obj.header[i] ] = val; // has key-value pairs where value is the current element of subArray and key is its equivalent (item at the same index) from header array return o; }, {}); }); } var obj = {"header":["SEOUL","BUSAN","NAMPODONG"],"data":[[38,"CAPITAL","M31"], [10,"OTHER","M01"]]}; var result = transform(obj); console.log(result); 

I think the responses above are good as they are, but here is an alternative using reduce in case you didn't know about it 我认为上面的回答是不错的,但是如果您不知道,这是使用reduce的替代方法

 var response = { "header": ["SEOUL", "BUSAN", "NAMPODONG"], "data": [ [38, "CAPITAL", "M31"] ] }; var result = response.header.reduce(function(accum, v, i) { accum[v] = response.data[0][i]; return accum; }, {}) console.log(result) 

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

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