Replace key in an array of object - javascript

I have an array of objects :
arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]
I have the name of the key I want to replace in my array :
var keyString = 'key1';
And I have the new name the key should take :
var newKey = 'newKey'
How to make my array this :
arrayOfObject = [{'newKey': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}]
JavaScript: Object Rename Key this can help me to rename the key but the thing is how to access the object first in my array that has the key1 key.
Note that keyString is random. So it's pointless to get it like arrayOfObject[0]
https://jsfiddle.net/tcatsx6e/

Check this solution:
var arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}];
var keyString = 'key1';
var newKey = 'newKey';
var newArray = arrayOfObject.map(function(item) {
if (keyString in item) {
var mem = item[keyString];
delete item[keyString];
item[newKey] = mem;
}
});
Please check this jsbin for a complete example.

This will return the index of the object you want to modify.
function(arr, keyString) {
for (var i = 0; i < arr.length; ++i) {
if (arr[i][keyString] !== undefined) {
return i;
}
}
}

Related

Convert two array into JSON object

I am trying to build JSON from two array. One array contains field_name and other contains field_value of corresponding field_name
var field_name = ["sys_id","country","calendar_integration","user_password","last_login_time"]
var field_value = ["6816f79cc0a8016401c5a33be04be441","United State","Outlook","Password1","2019-03-19 09:48:41"];
Expected output:
output = { "sys_id" : "6816f79cc0a8016401c5a33be04be441",
"country" : "United State",
"calendar_integration" : "Outlook",
"user_password": "Password1",
"last_login_time": "2019-03-19 09:48:41"
}
Anyone can help here, how to achieve this in JavaScript.
You can do that using reduce().Set value from field_name at index i as key and value as field_value at current index
var field_name = ["sys_id","country","calendar_integration","user_password","last_login_time"]
var field_value = ["6816f79cc0a8016401c5a33be04be441","United State","Outlook","Password1","2019-03-19 09:48:41"];
let res = field_name.reduce((ac,a,i) => ({...ac,[a]:field_value[i]}),{});
console.log(res);
You can also use forEach() in the same way.
var field_name = ["sys_id","country","calendar_integration","user_password","last_login_time"]
var field_value = ["6816f79cc0a8016401c5a33be04be441","United State","Outlook","Password1","2019-03-19 09:48:41"];
let obj = {};
field_name.forEach((a,i) => obj[a] = field_value[i]);
console.log(obj)
You can try something like that if both array are always with the same size :
let JSONOutput = {}
for (let i = 0; i < firstArray.length; i++) {
JSONOutput[firstArray[i]] = secondArray[i];
}
Check this solution
var output = {};
field_name.forEach((field, index) => {
output[field] = field_value[index];
});

How to concatenate values of duplicate keys

When reading a csv into a javascript dictionary, how can I concatenate values of what would otherwise be duplicate keys? I've seen answers for how to do this with bash, c#, and perl, but I haven't been able to find answers for Javascript. Here's what I have:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
This, obviously writes over existing keys. Instead, I want the key to be an array of the values. The csv basically looks like:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
And I want to output as:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}
Just check if your output already has the key, if so you add the new value to the array. Else you create an array.
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});
You could make it into an array and then push the content into that array
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});
Try this inside the for loop:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);
You can reduce the footprint of your code slightly if you use reduce:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}
DEMO

Removing "object having an array field" from an array in javascript

Here is my code:
var subMed = [ {med:'bm', sub:[ 'a' , 'b' ]} , {med:'bm', sub:[ 'c' , 'd' , 'e' ]} ];
var sal = [ {num:"1",amount:"500"} ];
var t = {Class:"1", subMeds:subMed, numOfSub:2, sals:sal };
var infoAcademic = [];
infoAcademic.push(t);
subMed = [ {med:'em', sub:[ 'p']} , {med:'bm', sub:[ 'r' , 's' ]} ];
sal = [ {num:"2",amount:"1500"},{num:"1",amount:"700"} ];
t = {Class:"1", subMeds:subMed, numOfSub:1, sals:sal };
infoAcademic.push(t);
var tempObj = infoAcademic[1]; // an object
var mediumSubjects = tempObj["subMeds"]; // an array
console.log(mediumSubjects);
for(i=0;i<mediumSubjects.length;i++){
var temp = {}; // object
temp = mediumSubjects[i];
if(temp["med"] == 'bm'){
tempObj["numOfSub"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
console.log("removing from the medSubjects list: ");
console.log(temp);
var removed = mediumSubjects.splice(i, 1);
break;
}
}
console.log("removed element: ");
console.log(removed);
console.log(mediumSubjects);
When I write this code this an online js editor https://js.do/ , the code gives result as per expected. But when I incorporate this code in a onclick function of my JSP page, no element gets removed from the mediumSubjects array. The removed element shows empty.
However, when I comment out this portion:
tempObj["numOfSubj"] = tempObj["numOfSub"] - temp["sub"].length;
var salArr = tempObj["sals"]; // array
var j = salArr.length;
if(salArr.length > 0){
while(j--){
var salObj = salArr[j]; // object
var howManySub = salObj["num"];
if(howManySub > tempObj["numOfSub"]){
salArr.splice(j,1);
}
}
}
the code surprisingly behaves as expected- it removes the element from the mediumSubjects array.
Is there any synchronization issue or something else? Why this sort of unusual behavior?
N.B. I need to remove elements from the array mediumSubjects, so delete won't work here.
Try this variant:
var newMedSub = medSub.filter(function(elem) {
return elem.med !== 'em';
});
It will help you to get a new array without unnessessary object.
All you actually need is to iterate over the outer array and in the body of this loop you need to iterate over the object keys.
for Example:
// removing med key from the array.
medSub.forEach(obj => {
for (let key in obj) {
if (key === 'med' && obj[key] === 'em') {
delete obj[key];
}
}
});
I hope this helps.

how can i transmission array to object with lodash?

I have an array like as below
var arr = [ 'type=A', 'day=45' ];
var trans = { 'type': 'A', 'day': 45 }
Please write easiest and most efficient way :)
You could split the string and check if the value isNaN for string or take the numerical value.
var array = [ 'type=A', 'day=45', 'bar=0' ],
object = Object.create(null);
array.forEach(function (a) {
var p = a.split('=');
object[p[0]] = isNaN(p[1]) ? p[1] : +p[1];
});
console.log(object);
The solution using Array.prototype.reduce() function:
var arr = [ 'type=A', 'day=45' ],
trans = arr.reduce(function(r, s){
var parts = s.split('=');
r[parts[0]] = isNaN(parts[1]) ? parts[1] : +parts[1];
return r;
}, {});
console.log(trans);
Iterate over each item in the array
Split on =
Add value to object, at key index
var arr = [ 'type=A', 'day=45' ];
var object = {};
for (var i = 0; i < arr.length; i++) {
var currentItem = arr[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
There's probably a million different ways to this, this way uses two different functions. the _.map() call runs on every element, splitting (and parsing) the element (if it matches a character regex). It then uses Lodash's .fromPairs function, which converts an array made up of 2 element arrays to return an object.
var arr = ['type=A', 'day=45'];
var obj = _.fromPairs(_.map(arr, function(item) {
var parts = item.split('=');
var digits = /^\d+$/;
if (digits.test(parts[1])) parts[1] = parseInt(parts[1]);
return parts;
}));
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

How To Get Multiple Array Value Based On Another Array In Javascript

I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));

Categories

Resources