Creating an array of JSON objects from another array of JSON objects - javascript

I have a JSON array like this:
[{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}]
I want to parse this and create a new array of objects which only have non-blank attributes without IDs, i.e:
[{FirstName:"John", SecondName:"Smith"},
{Company:"SomeComp", SecondName:"Kane"},
{Company:"Random", FirstName:"Tom"}]
What is the best way of doing this in Javascript?

You can use map
The map() method creates a new array with the results of calling a
provided function on every element in this array.
var companies = [{Company:"", FirstName:"John", SecondName:"Smith", ID:"2345"},
{Company:"SomeComp", FirstName:"", SecondName:"Kane", ID:"4363"},
{Company:"Random", FirstName:"Tom", SecondName:"", ID:"6454"}];
// This returns a new array
var newArray = companies.map(function(item) {
var obj = {};
for(var prop in item) {
if (item[prop] !== "" && prop !== "id" ) {
obj[prop] = item[prop];
};
}
return obj;
});
console.log(newArray);

This should do it
var input = JSON.parse("<YOUR JSON HERE>");
var output = [];
input.forEach(function(item) {
delete item.ID;
for (var prop in item) {
if (item.hasOwnProperty(prop) && item[prop] === "") {
item[prop] = undefined;
}
}
output.push(item);
});

Related

How to get the common values in an array

For example i am having an array of data as below
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
i need to list the same data as below in javascript
var arrDataSorted = ["40-25","50-48","30-25","40-23","40-45","40-50","40-50"]
need only the common data that replicates also the null to be removed.
What is the best solution to solve this.
You can try using Array.prototype.filter() to remove null values and Set to get the unique values. Finally use the Spread syntax (...) to transform the set result into an array.
Try the following way:
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var arrDataSorted = [...new Set(arrData.filter(i => i))];
console.log(arrDataSorted);
You can create a set from an array which will automatically remove duplicates:
let arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
let set = new Set(arrData);
This will still keep the null, which you can remove with a delete call, and convert back to array with the spread ... operator. The final code will be:
let set = new Set(arrData);
set.delete(null);
let distinctArr = [...set];
add the values into the set if the value is not null and convert it to array.
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
var setData = new Set();
for(var data of arrData) {
if(data) {
setData.add(data);
}
}
var arrDataSorted = [...setData];
console.log(arrDataSorted);
Add this function to your code:
function removeCommonValues(arr) {
let result = [];
for(let i=0; i < arr.length-1; ++i) {
if(result.includes(arr[i]) === false && arr[i] !== null)
result.push(arr[i])
}
return result
}
Usage:
removeCommonValues(["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]) // Return ["40-25", "50-48", "30-25", "40-23", "40-45", "40-50"]
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
var set = new Set();
for ( var i = 0 ; i< arrData.length;i++ ) {
if(arrData[i]!==null) {
set.add(arrData[i]);
}
}
var newArr = [...set]
You could use array built-in reducer method, in the next code i'm starting with an empty array, and i'm only returning the items that are not null and are not already in the array.
const data = arrData.reduce((state, value) => {
if(value && !state.includes(value)) {
return [...state, value];
}
return state;
}, [])
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"]
const output = [];
arrData.forEach(val => {
if(output.indexOf(val) === -1 && val !== null) {
output.push(val);
}
});
console.log(output);
The function can be in a separated file to be reused between multiple pages. Then you can call that function to filter distinct values that are not null.
var arrData = ["40-25",null,null,"40-25","50-48",null,"30-25","40-23","50-48","30-25",null,"50-48","40-45","40-45","40-45","40-50","40-50",null,null,null,null,null,"50-48"];
function fn(value,index,self){
return self.indexOf(value) === index && value;
}
console.log(arrData.filter(fn));

Angular search object array

What is the best way to search a particular parameter of an object array in Angular?
I populate my array from an Angular foreach :
$scope.arrayiwanttosearch = [];
angular.forEach(data, function(value, key) {
try{
var arrstring = new Array();
arrstring = value.img.split(',');
obj.name = value.name;
obj.selectedcolor = arrstring[0];
obj.colors = value.img;
obj.ischanging = false;
$scope.arrayiwanttosearch.push(obj);
}
catch(ex){
}
})
I can only use array.index of when its an array without objects, is there a way to do this without using a for loop? Im trying to find the index of the object that has the obj.name == "test"
Im trying to find the index of the object that has the obj.name ==
"test"
This is a straight use of findIndex.
var arrayiwanttosearch = [
{
name : "nottest"
},
{
name : "test"
}
];
var index = arrayiwanttosearch.findIndex(obj => obj.name === "test");
console.log(index);
You can use the native javascript 'filter' which will bring back all the matching members of the array, or 'find' which brings back the first one it finds, or 'findIndex';
// This finds the first matching array element with an object property === 2
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.find((item) => item.a === 2);
// The filter does the same but brings back all matching elements;
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.filter((item) => item.a === 2);
// The index result;
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.findIndex((item) => item.a === 2);
ES6 JS notation, but easy to adapt for ES5 JS.
You can use Array.prototype to get the index value in an array of objects.
var index = $scope.arrayiwanttosearch.indexOfname("test");
Array.prototype.indexOfname = function(name) {
for (var i = 0; i < this.length; i++)
if (this[i].name === name)
return i;
return -1;
}

Json - remove only key and assign value to parent key

{"empid":{"string":"31564604"},"joindate":{"date":2017-01-01}}
Convert the above json into below format using Java/Javascript. juzt need remove the datatype.
{"empid":"31564604","joindate":2017-01-01}
Another solution, using Array#reduce.
var obj = { empid: { string: 31564604 }, joindate: { date: '2017-01-01' }, nested: { nextLevel: { boolean: 1 } } },
newObj = Object.keys(obj).reduce(function(s, a) {
s[a] = obj[a][Object.keys(obj[a])]
return s;
}, {});
console.log(newObj);
You could use a recursive approach with an object for getting the types right.
function convert(object) {
var dataTypes = { boolean: true, string: true, date: true };
Object.keys(object).forEach(function (k) {
var key;
if (object[k] && typeof object[k] === 'object') {
key = Object.keys(object[k])[0];
if (key in dataTypes) {
object[k] = object[k][key];
} else {
convert(object[k]);
}
}
});
}
var object = { empid: { string: '31564604' }, joindate: { date: '2017-01-01' }, nested: { nextLevel: { boolean: true } } };
convert(object);
console.log(object);
If datatype is only specified for innermost element and not for the array or object then do it like.
var json = '{"empid":{"string":"31564604"},"joindate":{"date":"2017-01-01"},"a":[{"number":1}],"level1":{"level2":{"string":"abc"}}}';
// parse the string
var object = JSON.parse(json);
updateObj(object);
function updateObj(obj) {
// get all keys and iterate over them
Object.keys(obj).forEach(function(k) {
// get the nested object property
var key = Object.keys(obj[k])[0];
// update only if nested property is object
typeof obj[k][key] != 'object' && (obj[k] = obj[k][key]);
// recursively call the faction if the element is object
typeof obj[k] == 'object' && updateObj(obj[k]);
})
}
// convert back to JSON
console.log(JSON.stringify(object));
With Javascript, convert it to an object then update by simply iterating over all properties and finally stringify the object.
var json = '{"empid":{"string":"31564604"},"joindate":{"date":"2017-01-01"}}';
// parse the string
var obj = JSON.parse(json);
// get all keys and iterate over them
Object.keys(obj).forEach(function(k) {
// update the property with the nested object property value
obj[k] = obj[k][Object.keys(obj[k])[0]];
})
// convert back to JSON
console.log(JSON.stringify(obj));
UPDATE : For nested object use the same with recursive approach.
var json = '{"empid":{"string":"31564604"},"joindate":{"date":"2017-01-01"},"a":{"array":[{"number":1}]},"level1":{"object":{"level2":{"string":"abc"}}}}';
// parse the string
var object = JSON.parse(json);
updateObj(object);
function updateObj(obj) {
// get all keys and iterate over them
Object.keys(obj).forEach(function(k) {
// update the property with the nested object property value
obj[k] = obj[k][Object.keys(obj[k])[0]];
// recursively call the faction if the element is object
typeof obj[k] == 'object' && updateObj(obj[k]);
})
}
// convert back to JSON
console.log(JSON.stringify(object));
Given the data:
const oldJson = {"empid":{"string":"31564604"},"joindate":{"date":"2017-01-01"}};
ES6:
let newJson = {};
Object.keys(oldJson).forEach(key => {
newJson[key] = oldJson[key];
});
ES5:
var newJson = {};
Object.keys(oldJson).forEach(function(key) {
newJson[key] = oldJson[key];
});
My solution : only with ES6 feature so you have to use Babel
(function(){
const oldJson = {"empid":{"string":"31564604"},"joindate":{"date":"2017-01-01"}};
const newJson = Object.values( oldJson ).reduce( (acc, value) => Object.assign(acc, value), {})
console.log(newJson);
})();
Documentation :
Object.values
Object.assign
Array.reduce

how to get preferred array pushed in javascript

I am receiving data in object form. that object contains properties in which three keys are holding array values. I want to push concat those three array into one master Array. But should be in preferred sequence. Like
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
oneArray(obj,'make','type','power')
The master Array should have first 'make', 'type' and then 'power' keys Array from object. Right now it is coming in order which is given in obj
Fidde
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
var oneArray = function (obj,first,second,third){
var newObj = obj;
var list = [];
for(var key in newObj){
if (newObj[key] instanceof Array) {
if (!list) {
list = newObj[key];
}
else {
list = list.concat(newObj[key]);
}
}
}
newObj['all'] = list;
return newObj
}
console.log(oneArray(obj,'make','type','power'))
I'm not sure I have understood your question, but try this...
This onArray() function takes parameters that indicating priorities in orderly manner but first parameter.
var obj = {'type':['a','b'],'power':[500,700],'make':['2012','2015']}
var oneArray = function(obj) {
var newObj = obj;
var list = [];
var priorityList = arguments;
for( var i = 1 ; i < priorityList.length ; i++ ) {
if( newObj[ priorityList[i] ] instanceof Array ) {
for( var key in newObj[ priorityList[i] ] ) {
list.push( newObj[ priorityList[i] ][ key ] );
}
}
}
newObj['all'] = list;
return newObj;
}
console.log(oneArray(obj,'make','type','power'));

What’s the lodash equivalent of this nested object creator function?

So, I have this fuction that’s creating nested objects based on an array ok keys and I’m wondering how I could accomplish the same thing using lodash?
// nest
var nest = function (obj, keys, v) {
if (keys.length === 1) {
obj[keys[0]] = v;
} else {
var key = keys.shift();
obj[key] = nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v);
}
return obj;
}
// sample data
var keys = ['user','name','fullName'];
var value = 'John Smith';
// create nested object
var obj = {};
obj = nest(obj, keys, value);
// log out new nested object
console.log(obj);
// include lodash somewhere...
// nest
var nest = function () {
return _.set(obj, path, value);
}
// sample data
// var keys = ['user','name','fullName']; can use a path now!
var path = 'user.name.fullName';
var value = 'John Smith';
// create nested object
var obj = {};
obj = nest(obj, path, value);
// log out new nested object
console.log(obj);

Categories