How to do mapping for two objects and array in javascript - 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.
{"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. 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.
key value : A
header : SEOUL BUSAN NAMPODONG
data : 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.

Create a variable & loop over the object.header to get each key and object.data[0] to get its value
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.
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. If it's not – you have to map though it's elements first and only then reduce.

You can use zipObj from Ramda library.
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:
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
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)

Related

How to accumulate all values inside a 2D array that share the same field?

I have a 2D array that contains values like this:
var array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
For every nested array that has the same date value (the first element), I want to add up the second value to have something like this:
arrayAdd = [["10/10/2020","1400"],["O7/10/2020","200"],["03/10/2020","100"]]
How can I do this?
var array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
function fromEntries (iterable) {
return [...iterable].reduce((obj, [key, val]) => {
obj[key] = String(obj[key] ? +obj[key] + +val : val)
return obj
}, {})
}
console.log(fromEntries(array))
Step by step:
Create an empty object/map.
Iterate over your array.
Get the first element of each item in the array (date) and check if that key is already in the object.
If it is not, you add it. The value will be the second element (the number).
If it is there already, you increment the value.
Object.entries will turn that object into an array with the shape you want, as you can see below:
const obj = {
"10/10/2020": "1400",
"O7/10/2020": "200",
"03/10/2020": "100",
};
console.log(Object.entries(obj));
.as-console-wrapper {
max-height: 100% !important;
}
This should help you get started.
you can do this
const data = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
const result = Object.entries(data.reduce((res, [key, value] ) => {
return {
...res,
[key]: (res[key] || 0) + Number(value)
}
}, {}))
console.log(result)
There are a couple ways to handle this question.
You can either compare the string values of each date to see if they are the same, or you can convert them to date objects and compare them that way. Here's a link to the MDN document that shows how you can get a primitive value for the date.
I'm going to use the string value because, in this case, I'm going to assume that all dates are coming in a consistent format.
let array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
let arrayAdd = []
for (let valuePair of array) {
// grab just the date value
let date = valuePair[0];
// check to see if pair is in arrayAdd
let foundPair = arrayAdd.find(el => el[0] === date)
// will return undefined if nothing found
if (!foundPair) {
// if nothing found, we push the entire value and date pair
arrayAdd.push(valuePair);
} else {
// few things happening here..
// we have to convert each value to number to properly add
// once they're added, we convert that new value back into a string
// and then set the value of the found pair to that new string.
foundPair[1] = (Number(valuePair[1]) +
Number(foundPair[1])).toString();
}
}
console.log(arrayAdd);

How do I join two array and create json array of objects

SO I have array1 with values ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] and another array 2 with values ["title":"firsttitle", "title":"second","title":"thirdtitle"]
Now lets say using javascript i want to save it as json object.
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
I trying looping and concat but didn't work properly.
array1= ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] ;
array2 = ["title":"firsttitle", "title":"second","title":"thirdtitle"];
Get array with json objects
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
In JavaScript an array has just values, in you examples the array is invalid since you try to add direct key: values elements . i.e.
["folderid":"DTSZ"] // invalid !! (notice semicolon)
["folderid", "DTSZ"] // VALID (notice comma)
If you want to translate to a valid array and then to an object, you could use something like entries, which are array of arrays.
Let's take your first example and convert it to entries:
const arr1 = [["folderid", "DTSZ"], ["folderid", "IEACF6FVGG"], ["folderid","IEACKQC6A"]]
Then to convert this to object you can use Object.fromEntries just like this:
const obj1 = Object.fromEntries(entries);
So, focus first to convert your initial invalid arrays to entries, and then the job is done!
use the following code.
var a = [{ "folderid": "DTSZ" }, { "folderid": "IEACF6FVGG" }, { "folderid": "IEACKQC6A" }]
var b = [{ "title": "firsttitle" }, { "title": "second" }, { "title": "thirdtitle" }]
var newObject = a.map((o, index) => {
const temp = Object.assign(o, b[index]);
return temp;
});
console.log('output ---- ', newObject)

How to add multiple values to existing keys for an array of objects?

I am trying to use reduce() for getting economy rate for a particular wicket.
Example data:
var data = [
{wicket:0, econ:20 },
{wicket:1, econ:10 },
{wicket:3, econ:45 },
{wicket:0, econ:15 },
{wicket:1, econ:32 }
]
I want reduce() method to return an array of objects which will look like this:
0: 20, 15
1: 10, 32
3: 45
What I am trying to do is initialize accumulator with object but in reduce() method I am not able to figure out how can I get the required array of objects with key value as wicketand values as economy.
My code:
const Economy = data.reduce( (a, {econ, wicket}) => {
a[wicket].push(econ);
},{})
I get undefined behaviour with above code.
If your data was meant to be an Array and not an Object (which it isn't right now, at least not a valid one) :
let data = [
{wicket:0, econ:20 },
{wicket:1, econ:10 },
{wicket:3, econ:45 },
{wicket:0, econ:15 },
{wicket:1, econ:32 }
];
let result = data.reduce((acc, curr) => {
if(acc[curr.wicket]) acc[curr.wicket].push(curr.econ);
else acc[curr.wicket] = [curr.econ];
return acc;
},{});
console.log(result);
You can use group the array using reduce like:
var data = [{"wicket":0,"econ":20},{"wicket":1,"econ":10},{"wicket":3,"econ":45},{"wicket":0,"econ":15},{"wicket":1,"econ":32}];
var result = data.reduce((c, v) => {
c[v.wicket] = c[v.wicket] || []; //Initiate the property as empty array of it does not exist
c[v.wicket].push(v.econ);
return c;
}, {});
console.log(result);
|| is an OR operator.
This means if c[v.wicket] exist, it will assign it to c[v.wicket] again. If it does not, assign an empty array []
c[v.wicket] = c[v.wicket] || [];

Remove last letter from map value

So I'm getting this from backend:
{"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}}
I use Object.Keys to narrow down the contents to:
Drake,Ola,b,d
Which I then map to give:
[{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}]
Which is then used on my Angular Front-end as .id. I want to remove the last letter from each value i.e leaving Drak,Ol etc. I've tried many ways but have failed, how can I achieve this please so that the id has those values?
EDIT
I also want to now get that value that was cut AND add it such that the end product will be [{"id":"Drak",valueThatWasCut:"e"}]
You could iterate the object's keys and build with the short string a new object.
var data = {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}},
ids = Object.keys(data.Item.Buddy.contents).reduce(function (r, k) {
var n = k.slice(0, -1);
return n ? r.concat({ id: n }) : r;
}, []);
console.log(ids);
Perhaps something like :
var arr = [{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}];
var result = arr.map(x => x.id.slice(0,-1));
console.log(result); // [ 'Drak', 'Ol', '', '' ]
Create a temporary contents object and change in that.
Then just set this in the original object. ES6 spread operators would save the rest of data without respecifying all keys and values.
let items = {"Item:{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}};
let contents = items.Item.Buddy.contents;
let contentsNew = Object.keys(contents).map((content) => {
return {[content.substring(0, content.length-1)]: content.substring(0, content.length-1), valueThatWasCut: content[content.length-1]};
});
items = {...items, Item: {...items.Item,Buddy:{...items.Item.Buddy,contents: contentsNew}}};
console.log(items);

generate js key-value object from string

I got a very common question but with a twist which is the reason for this post:
I want to create a key,value object from a string.
my string looks like this:
01§§foo§§bar§§someLink
(i can change the delimiter symbols to whatever i want, if there should be somehow a very tight solution with a specific symbol)
now, i want a key value object and most questions about this problem already got the datapair in the string,(like "id:01,title:foo") but thats not the case in my problem.
i want to generate something like this:
var modules = [
{"ID":"01", "title":"foo", "description":"bar","link":"someLink"},
//more entries from more strings
];
the reason for the key,value object is, that there are more of these strings which I convert from a database. I want it to be in a key,value object so its easier to work with the data later in my tool.
Thank you in advance
You could use Array#split for the string and an array for the keys.
var string = '01§§foo§§bar§§someLink',
moduleKeys = ["ID", "title", "description", "link"],
object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
console.log(object);
A methode for multiple strings.
function getData(array) {
var moduleKeys = ["ID", "title", "description", "link"];
return array.map(function (string) {
var object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
return object;
});
}
var strings = ['01§§foo§§bar§§someLink', '02§§foo§§bar§§someLink'];
console.log(getData(strings));

Categories