Converting an array of strings into an array of objects - javascript

I have an array of strings:
["14: London", "15: Manchester", "16: Bristol"]
I need to change it into an array of objects that would look like this:
[{14: "London"}, {15: "Manchester"}, {16: "Bristol"}]
I assume that the best way to go about this is to first iterate over the array and split each string and then convert it into an object before pushing back into an array.
I can't really figure out how to make it work though, so any help would be much appreciated.
Thanks for your time

Use Array#map method to generate the array.
var arr = ["14: London", "15: Manchester", "16: Bristol"];
// iterate over the array
var res = arr.map(function(v) {
// split the value based on `:`
var splitArr = v.split(':'),
// initialize an object
obj = {};
//define the property value
obj[splitArr[0].trim()] = splitArr[1].trim();
// return the generated object
return obj;
})
console.log(res);

You can map it
var arr = ["14: London", "15: Manchester", "16: Bristol"];
var obj = arr.map(d => {
var split = d.split(": ");
return {
[split[0]] : split[1]
}
});

var arr = ["14: London", "15: Manchester", "16: Bristol"];
var makeObjectFromArray = function(arr) {
if (Object.prototype.toString.call(arr) !== '[object Array]') return arr;
var objects = [];
for (var i = 0, length = arr.length; i < length; i++) {
var obj = arr[i].split(":");
var temp = {};
var key = (typeof obj[1] === 'string') ? obj[0].trim() : obj[0];
var value = (typeof obj[1] === 'string') ? obj[1].trim() : obj[1];
temp[key] = value;
objects.push(temp);
}
return objects;
};
console.log(makeObjectFromArray(arr))

You could also do like this so you can know when your object already has a key/value pair with the same key:
var testArray = ["14: London", "14: London", "15: Manchester", "16: Bristol"];
var testObj = {};
var length = testArray.length;
for ( var i = 0; i < length; i++ ) {
var newTestArray = testArray[i].split(":");
if ( testObj[newTestArray[0]] === undefined ) {
testObj[newTestArray[0]] = newTestArray[1];
} else {
console.log("key: " + newTestArray[0] + " already exists!");
}
}

Related

Convert Javascript Array to JSON User Defined Key/Value Pair

I need to take a string from a text input and convert it from an array to a JSON object.
let orderInputArray = ["key1", "value1", "key2", "value2"];
let json = {}
let key,value;
orderInputArray.forEach(function(keyValue) {
json[key] = keyValue.value;
});
let orderInputJSON = JSON.stringify(orderInputArray);
I need it to look like:
[{"key1": "value1"}, {"key2": "value2"}]
I'm not quite sure how to do this with the for each loop. Can anyone shed some light?
This is not the ideal way to create an object, but you can skip the key, create an object with the key/value using the current index (i), and push it to the result (orderInputObjects):
const orderInputArray = ["key1", "value1", "key2", "value2"];
const orderInputObjects = [];
orderInputArray.forEach(function(v, i, a) {
if(i % 2) orderInputObjects.push({ [a[i - 1]]: v });
});
console.log(orderInputObjects);
You can use a simple for loop and increment by 2 instead of 1
function arrayToKeyValue(array) {
let updated = [];
for (let i = 0; i < array.length; i += 2) {
const key = array[i];
const value = array[i + 1];
updated.push({ key: value });
}
return updated;
}
forEach uses a call back function, therefore it is not guaranteed to finish before the let orderInputJSON = JSON.stringify(orderInputArray); in your code.
Try using
var i;
for (i =0; i < orderInputArray.length; i=i+2){
//create object here using orderInputArray[i] as key and orderInputArray[i+1] as value
}
You can use filter to create an array of odd and even , then use reduce function to create the array of object
let orderInputArray = ["key1", "value1", "key2", "value2"];
let vals = orderInputArray.filter(function(item, index) {
return index % 2 === 1
});
let keys = orderInputArray.filter(function(item, index) {
return index % 2 === 0
}).reduce(function(acc, curr, index) {
acc.push({
[curr]: vals[index]
})
return acc
}, []);
console.log(keys)
You can do this with reduce as well
let orderInputArray = ["key1", "value1", "key2", "value2"];
var l = orderInputArray.length;
var jsobj = orderInputArray.reduce(function(acc, v, i) {
var o = {};
if (i % 2 === 0 && i < l - 1) {
o[v] = orderInputArray[i + 1];
acc.push(o)
}
return acc;
}, []);
console.log(JSON.stringify(jsobj))
Here my solution with splice:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var json = {};
while(fruits.length > 0){
let a = fruits.splice(0,2)
console.log(a)
json[a[0]] = a[1]
}
console.log(json)
let orderInputArray = ["key1", "value1", "key2", "value2"];
jsonArray = [];
orderInputArray.forEach((item, i, a)=> {if(i%2 === 0) jsonArray.push({item:a[i+1]})});
console.log(jsonArray)

Sum of same object name in javascript

Hi friends I'm beginner for javascript how i sum same n no's of object name corresponding value and push the result to new array.see this is sample object
var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
but i expect this output [UK:{'delivered':20,'due':22},US:{'delivered':10,'due':11}],so please help me what i'll do next
You can first create array of objects and then reduce() to return one object.
var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
var result = [obj_1, obj_2, obj_nth].reduce(function(r, e) {
if(!r[e.team_name]) {
r[e.team_name] = {delivered:0,due:0}
}
r[e.team_name].delivered += e.delivered
r[e.team_name].due += e.due
return r
}, {})
console.log(result)
const newArray = initialArray.map(({team_name, ...restProps}) => {
return {
[team_name]: {...restProps}
};
});
See:
Arrow functions
Spread operator
Array.prototype.map
Computed property names
var obj_1 ={'delivered':10,'due':11,'team_name':'UK'};
var obj_2 ={'delivered':10,'due':11,'team_name':'US'};
var obj_nth ={'delivered':10,'due':11,'team_name':'UK'};
function sum_all() {
var sum={};
for(var i=0;i<arguments.length;i++) {
obj = arguments[i];
if (!sum[obj.team_name]) {
sum[obj.team_name]={'delivered':0,'due':0};
}
sum[obj.team_name].delivered += obj.delivered;
sum[obj.team_name].due += obj.due;
}
return sum;
}
var sum = sum_all(obj_1,obj_2,obj_nth);
console.log(sum);
Your console output will be:
sum
Object
UK: Object
delivered: 20
due: 22
US: Object
delivered: 10
due: 11
Store these objects in an array, such as:
var myObjects = [
{'delivered':10,'due':11,'team_name':'UK'},
{'delivered':10,'due':11,'team_name':'US'},
{'delivered':10,'due':11,'team_name':'UK'}
];
Create a new object in which you will store your results:
var results = {};
Then iterate through the array with a for loop (as it is generally faster) and add the other properties according to team_name:
for (var i = 0; i <= myObjects.length; i++) {
if (typeof results[myObjects[i].team_name] !== undefined) {
results[myObjects[i]].delivered += myObjects[i].delivered;
results[myObjects[i]].due += myObjects[i].due;
} else {
// Set 0 to these properties if the entry didn't exist
results[myObjects[i]].delivered = 0;
results[myObjects[i]].due = 0;
}
}

Javascript make an object from array of strings

I have an array like this: var arr = ["1:a", "2:b", "3:c"];
From above array I want an object: var obj = { "1": "a", "2": "b", "3": "c" }
I am doing:
var obj = {}
$.each(arr, function (i, value) {
var valueSplit = value.split(':');
// I don't know how to make the object
});
Edit:
My Question is mark as duplicate, while the question I asked is totally opposite of the marked duplicate question.
From your code, in place of the comment you could write
obj[valueSplit[0]] = valueSplit[1];
This could be written as a simple reduce:
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
var arr = ["1:a", "2:b", "3:c"];
var obj = arr.reduce(function(x,y) { return z = y.split(':'), x[z[0]]=z[1], x; }, {});
document.write(JSON.stringify(obj));
Just add the assignment.
var obj = {}
$.each(arr, function (i, value) {
var valueSplit = value.split(':');
obj[valueSplit[0]] = valueSplit[1];
});
Simply try this
var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){
var keyVal = val.split( ":" );
map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});
map is the object you are looking for.
DEMO
var arr = ["1:a", "2:b", "3:c"];
var map = {};
arr.forEach( function(val){
var keyVal = val.split( ":" );
map[ keyVal[ 0 ] ] = keyVal[ 1 ];
});
document.body.innerHTML += JSON.stringify( map, 0, 4 );

How do I return array of duplicate strings in array?

I need a function that takes in an array and will return an array with all the duplicates. I would prefer to use underscore if possible.
given the array:
[
"apple",
"apple",
"pear",
"pear",
"kiwi",
"peach"
]
I need to return an array
[
"apple",
"pear"
]
Many of the methods I've found will return a boolean and not an array of the duplicates.
For example
var fruits = ["apple","apple"];
var uniq_fruits = _.uniq(fruits);
var duplicates_exist = (fruits.length == uniq_fruits.length);
You could use _.countBy to get the word frequencies and then use _.reduce to collect up the values with a frequency greater than one:
function collect_dups(a, n, word) {
if(n > 1)
a.push(word);
return a;
}
var dups = _(words).chain()
.countBy()
.reduce(collect_dups, [])
.value();
Demo: http://jsfiddle.net/ambiguous/gKmfh/1/
Turn your list into a map, then turn the map into a list.
var fruits = ["apple", // ... ];
function fruitCounter(countMap, fruit) {
if (countMap[fruit] == null)
countMap[fruit] = 1;
else
countMap[fruit]++;
return countMap;
}
function dupFinder(dupList, count, fruit) {
if (count > 1)
dupList.push(fruit);
return dupList;
}
var dups = _.reduce(_.reduce(fruits, fruitCounter, {}), dupFinder, []);
It's sort-of unfortunate that there's nothing really like "filter" for the properties of an object, but it's not too bad with "reduce".
edit — a comment from someone better at Underscore than me points out that the inner "reduce" could be replaced by a simpler "countBy":
var dups = _.reduce(_.countBy(fruits, function(f) { return f; }), dupFinder, []);
var common = function(array){
var tally = function(array){
var make_object = {};
_.each(array, function(item){
make_object[item] = (typeof make_object[item] == "undefined") ? 1 : make_object[item] + 1;
});
return make_object;
}(array);
var duplicates = function(obj){
var duplicates = [];
_.each(obj, function(value, key){
if(value > 1){
duplicates.push(key);
}
});
return duplicates;
}(tally);
return duplicates;
};
The idea is very straight forward. Group the items by its value and then find which group having more than 1 items. Finally pick only one item from each group.
lst = [ "apple", "apple", "pear", "pear", "kiwi", "peach"];
var result = _.chain(lst)
.groupBy(function (i) { return i; })
.filter(function (v, k) { return v.length > 1; })
.map(function(v){return v[0]; })
.value();
>>["apple", "pear"]
where arr is your input, you just check to see if the element is a key on the obj object - if it is, pass it to the output array and reloop, otherwise add the key to the object:
function findDupes(arr) {
var obj = {}, newArr = [];
for (var i = 0, l = arr.length; i < l; i++) {
if (obj[arr[i]]) { newArr.push(arr[i]); continue; }
obj[arr[i]] = true;
}
return newArr;
}
var dupes = findDupes(arr);
Giving you have a simple one level array of strings, I would suggest to sort an array first and then loop through it trying to compare current item with the next one.
Something like this:
var fruit = [
"apple",
"apple",
"apple",
"pear",
"pear",
"cantalope"
];
var common = function(array){
var mySortedArray = array.sort();
var myResultArray = [];
for (var i = 0; i < mySortedArray.length - 1; i++)
if ( (mySortedArray[i + 1] == mySortedArray[i]) &&
(mySortedArray[i] != myResultArray[myResultArray.length-1]) )
myResultArray.push(mySortedArray[i]);
return myResultArray;
};
alert(common(fruit));
I started from this function : https://stackoverflow.com/a/840849/1636522
function getDuplicates(arr) {
var i,
len = arr.length,
out = [],
obj = {};
for (i = 0; i < len; i++) {
switch (obj[arr[i]]) {
case undefined: obj[arr[i]] = 1; break;
case 1: obj[arr[i]] = 2; out.push(arr[i]); break;
}
}
return out;
}

Javascript difference with subarrays

I am working on a program, and would like a little insight to Javascript difference. In my program, I have a blacklist array which contains values that are not allowed to be in my final result, like below:
blacklist = ["One", "Two", "Four"]
someArr = ["One", "Three", "Five", "Two", "One"]
//Desired result = ["Three", "Five"]
I found a great tip from another Stack question (the code shown below).
Array.prototype.diff = function(a) {
return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};
////////////////////
// Examples
////////////////////
[1,2,3,4,5,6].diff( [3,4,5] );
// => [1, 2, 6]
["test1","test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);
// => ["test5", "test6"]
The problem is that I need to compare an array of strings to a specific key in a 3 dimensional array. Here is how I have it structured:
Array1 = [collab1: "Name, Someone's",
collab2: "Else, Somebody",
...: ...],
[collab1: "Else, Somebody",
collab2: "Thornton, Billy Bob",
...: ...];
Array2 = ["Name, Someone's", "Else, Somebody", "Thornton, Billy Bob"]
I would like to use the diff class to check collab1 for each index against Array2. Is this possible?
Solution to compare any 2 objects:
var
array_tools = {};
array_tools.filter = function(Arr,fun){
if(typeof Array.prototype.filter === 'undefined'){ // Допиливание функциональности массивов для IE
//filter = function( fun ){ // , thisp
var len = Arr.length;
if(typeof fun != "function") throw new TypeError();
var res = [], thisp = arguments[1];
for(var i=0;i<len;i++){
if(i in Arr){
var val = Arr[i]; // in case fun mutates this
if(fun.call(thisp, val, i, Arr)) res.push(val);
}
}
return res;
}
else{
return Arr.filter(fun);
}
};
var compare_objects = function( firstObj, secondObject ){
var get_keys = function(O){
var A = [];
for(var key in O) A.push(key);
return A;
},
keysFirstObj = get_keys(firstObj),
keysSecondObject = get_keys(secondObject);
if( keysFirstObj.length != keysSecondObject.length ){
return false;
}
return !array_tools.filter( keysFirstObj, function(key){
if( typeof firstObj[key] == "object" || $.isArray(firstObj[key]) ){
return !compare_objects(firstObj[key], secondObject[key]);
}
else{
return firstObj[key] !== secondObject[key];
}
} ).length;
}
To compare 2 objects: compare_objects(Obj1, Obj2). If this will be true - they are equal.
ADDITION
$.isArray is from jQuery. If you don't need jQuery - open it's full source and copy only this tool.

Categories