var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"SAMEERA"}];
I want output to be like this:
[{"name":"SAM","surname":"SAMEERA","location":"mumbai","age":"22"}];
using javascript and underscorejs
My attempt is as below:
var workingValues = _.filter(array1, function(item){ return item});
console.log(workingValues);
var validItems = [];
for(var i =0 ; i < array2.length; i++){
var item = array2[i];
console.log(item);
var findItems = _.filter(array1,function(ite) {
return ite.name.toUpperCase() == item.name.toUpperCase() && ite.surname.toUpperCase() == item.surname.toUpperCase()});
validItems.push(item);
console.log(findItems);
}
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"SAMEERA"}];
var result = [{...array1[0],...array2[0]}];
console.log(result);
You can try this
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"},{"name":"sam123","surname":"sameera123","location":"mumbai","age":"22"} ];
var array2 =[ {"name":"SAM","surname":"SAMEERA"},{"name":"SAM123","surname":"SAMEERA123"}];
var ret = [];
for(var i = 0; i < array1.length; i += 1) {
var newArray = array2.filter(function (el) {
return el.name.toUpperCase() == array1[i].name.toUpperCase() && el.surname.toUpperCase() ==array1[i].surname.toUpperCase();
});
if(newArray.length ==0)
{
ret.push(array1[i]);
}
else
{
array1[i].name = newArray[0].name; //change valuse
array1[i].surname = newArray[0].surname; //change valuse
ret.push(array1[i]);
}
};
console.log(ret);
Based on the limited data you've provided.
var array1 = [ {"name":"sam","surname":"sameera","location":"mumbai","age":"22"}];
var array2 =[ {"name":"SAM","surname":"sameera"}];
console.log( _.extend(array2, array1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
var array1 = [{
"name":"sam",
"surname":"sameera",
"location":"mumbai",
"age":"22"
}];
var array2 =[{
"name":"SAM",
"surname":"sameera"
}];
var mergearray= array1 .concat(array2);
Related
How do i create a multi-dimensional array from different javascript variables ?
For example, i have these three variables
var pdate = "|2019-12-26|2019-12-26|2019-12-26"
var products_id = "3354|5009|61927"
var products_category = "ENERGETICS|CASIO|SEIKO"
And i would like to transform them into this
var products_list = []
[0] = {pdate:"2019-12-26",products_id:"3354",products_category:"ENERGETICS"}
[1] = {pdate":"2019-12-26",products_id:"5009",products_category:"CASIO"}
[2] = {pdate:"2019-12-26",products_id:"61927",products_category:"SEIKO"}
Any ideas ?
Thanks
You can use the function split to separate the datas:
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
var arrayPdate = getData(pdate);
var arrayProducts_id = getData(products_id);
var arrayProducts_category = getData(products_category);
var result = []
for (let i = 0; i < arrayPdate.length; i++) {
let jsonObject = {
pdate: arrayPdate[i],
products_id: arrayProducts_id[i],
products_category: arrayProducts_category[i]
}
result.push(jsonObject)
}
console.log(result);
function getData(c) {
return c.split("|")
}
You need use .split function on your string and then use loop with array index for others.
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
pdate = pdate.split('|');
products_id = products_id.split('|');
products_category = products_category.split('|');
let arr = [];
for(let i=0; i<pdate.length; i++) {
arr.push({
pdate: pdate[i],
products_id: products_id[i],
products_category: products_category[i]
});
}
console.log(arr);
Here's my input
var id = '1,2,3';
var name = 'a,b,c';
var value = 'x,y,z';
How can i construct a array like this
[
{
"id" : "1",
"name" : "a",
"value" : "x",
}
,
{
"id" : "2",
"name" : "b",
"value" : "y",
}
,
{
"id" : "3",
"name" : "c",
"value" : "z",
}
]
I tried like this
var newArray = [];
newArray.push({'id':id,'name':name,'value':value })
But it gives, a single array with comma seperated value.
How can i do this Pls help
Note : I prefer only javascript
You could iterate the given strings, split them and assign the values to an object in an array.
var id = '1,2,3',
name = 'a,b,c',
value = 'x,y,z',
keys = ['id', 'name', 'value'],
result = [];
[id, name, value].forEach(function (a, i) {
a.split(',').forEach(function (b, j) {
result[j] = result[j] || {};
result[j][keys[i]] = b;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use:
var id_split = id.split(',');
var name_split = name.split(',');
var value_split = value.split(',');
var newArray = [];
for(var i = 0; i < id_split.length; i++){
newArray.push({'id':id_split[i],'name':name_split[i],'value':value_split[i] })
}
This of course only works if the arrays are all the same length
If you know the elements length beforehand
var allIDs= '1,2,3';
var allNames= 'a,b,c';
var allValues= 'x,y,z';
var tmpArray = [];
for(var i=0;i<3;i++)
tmpArray.push(new {id: allIDs.split(',')[i] , name: allNames.split(',')[i], value: allValues.split(',')[i] });
But for a more generic solution, assuming that your comma sepparated string will always match in length
var allIDs= '1,2,3';
var allNames= 'a,b,c';
var allValues= 'x,y,z';
var tmpArray = [];
allIDs = allIDs.split(',');
allNames =allNames.split(',');
allValues = allValues.split(',');
for(var i=0;i<3;i++)
tmpArray.push(new {id: allIDs[i] , name: allNames[i], value: allValues[i] });
I would do as follows;
var id = '1,2,3'.split(","),
name = 'a,b,c'.split(","),
value = 'x,y,z'.split(","),
result = id.map((e,i) => ({id: e, name: name[i], value: value[i]}));
console.log(result);
var id = '1,2,3';
var name = 'a,b,c';
var value = 'x,y,z';
$('.resultsDiv').html(JSON.stringify(yourFun()))
function yourFun() {
ida = id.split(',');
namea = name.split(',');
valuea = value.split(',');
var returnvar = [];
for (var i = 0; i < ida.length; i++) {
returnvar.push({
"id": ida[i],
"name": namea[i],
"value": valuea[i]
});
}
return returnvar;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultsDiv"></div>
First, just split the lists into arrays, then you can perform a loop or use something like map/reduce to generate the compiled array.
var id = '1,2,3';
var name = 'a,b,c';
var value = 'x,y,z';
var idArray = id.split(',');
var nameArray = name.split(',');
var valueArray = value.split(',');
var newArray = idArray.map((id,i) =>
({ id: id, name: nameArray[i], value: valueArray[i] })
);
console.log(newArray);
I have this code: (it reads a folder of mp3 files and retrieves all paths)
var base = "../media/audio/";
var arr1 = [
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"},
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"},
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
];
I want to get this:
var arr2 = [
[{
category:"Numbers",
path:[
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"}
]
}],
[{
category:"Letters",
path:[
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"}
]
}],
[{
category:"Color",
path:[
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
]
}]
];
Find every category after the 'base' string, split them in array, inside each array and object with category and path property.
Here you go.
var output = document.getElementById("output");
function splitSearch(base, arr1) {
var categoryList = {};
var baseLen = base.length;
// Split paths into categories
arr1.forEach(function(inPath) {
var subPath = inPath.path.substr(baseLen);
var category = subPath.split("/")[0];
if (!categoryList.hasOwnProperty(category)) {
categoryList[category] = [];
}
categoryList[category].push(inPath);
});
// Transform categoryList into array format requested
var arr2 = [];
for (var category in categoryList) {
arr2.push({ category: category, path: categoryList[category] });
}
return arr2;
}
var base = "../media/audio/";
var arr1 = [
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"},
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"},
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
];
var result = splitSearch(base, arr1);
output.innerHTML += JSON.stringify(result);
<div id="output" />
This is what you are looking for:
var arr1 = [
{path:"../media/audio/Numbers/Cat1/01.mp3"},
{path:"../media/audio/Numbers/Cat1/02.mp3"},
{path:"../media/audio/Numbers/Cat1/03.mp3"},
{path:"../media/audio/Numbers/Cat1/04.mp3"},
{path:"../media/audio/Letters/Cat1/01.mp3"},
{path:"../media/audio/Letters/Cat1/02.mp3"},
{path:"../media/audio/Letters/Cat1/03.mp3"},
{path:"../media/audio/Color/Cat1/01.mp3"},
{path:"../media/audio/Color/Cat1/02.mp3"},
{path:"../media/audio/Color/Cat1/03.mp3"}
];
var basePath = "\.\.\/media\/audio\/";
var regex = new RegExp('^' + basePath + '(.*?)\/');
var categories = {}, arr2 = [];
for (var i=0, x=arr1.length; i < x; i++) {
var category = arr1[i].path.match(regex)[1];
if (!categories[category]) {
arr2.push({
category : category,
path : []
});
categories[category] = true;
}
for (var ii=0, l = arr2.length; ii < l; ii++) {
if (arr2[ii].category == category) {
arr2[ii].path.push(arr1[i]);
break;
}
}
}
Could probably be cleaned up a bit but should get you where you need to go
I know this works (returns true)
var arr1 = [1, 'a', 2, 'b', 3];
var arr2 = [1, 2, 3];
var isSuperset = arr2.every(function (val) { return arr1.indexOf(val) >= 0; });
However say array1 consists of objects, and I want to check array2 against a certain property of the object:
var object1 = {name:'one'}
var object2 = {name:'two'}
var object3 = {name:'three'}
var arr1 = [object1,object2,object3];
var arr2 = ['one','two'];
var isSuperset = arr2.every(function (val) { return arr1.indexOf(val) >= 0; });
How can I ensure the every function checks against the name property?
var object1 = {name: 'one'};
var object2 = {name: 'two'};
var object3 = {name: 'three'};
var arr1 = [object1,object2,object3];
var arr2 = ['one','two'];
// solution
var names = arr1.map(function(obj) {
return obj.name;
});
var isSuperset = arr2.every(function(val) {
return names.indexOf(val) >= 0;
});
alert(isSuperset);
In my below code Im am not able to fetch data within array
var str = "Service1|USER_ID, Service1|PASSWORD"
var str_array = str.split(',');
console.log(str_array)
for(var i = 0; i < str_array.length; i++)
{
str_array[i] = str_array[i].split('|');
}
console.log(str_array)
This is the response from above code
/* [ [ 'Service1', 'USER_ID' ],
[ 'Service1', 'PASSWORD' ] ]*/
I want response to be in two different array like below
var array1 = ['Service1']
var array2 = ['USER_ID','PASSWORD']
Any help on this will be really helpful
Since you're on Node, you can do this:
var str = "Service1|USER_ID, Service1|PASSWORD";
var result = str.split(',').reduce(function(collected,splitByComma){
var splitData = splitByComma.split('|');
var key = splitData[0].replace(/\s+/gi,''); //Might want to improve this "trim"
var data = splitData[1];
if(!collected.hasOwnProperty(key)) collected[key] = [];
collected[key].push(data);
return collected;
},{});
console.log(JSON.stringify(result)); //{"Service1":["USER_ID","PASSWORD"]}
//result.Service1[0] == USER_ID
//result.Service1[1] == PASSWORD
It's not wise to place stuff in separate places. You could have them under an object key though. If service name is variable, then you could do:
var serviceName = "Service1";
result[serviceName][0] == USER_ID
result[serviceName][1] == PASSWORD
As I have understand your question, you will want an array associated with each service key, to be able to do
services.service1
and get ['username', 'password' ] ?
If so, here's a solution:
var str = "Service1|USER_ID, Service1|PASSWORD".replace(', ', ',').split(','), //[ 'Service1|USER_ID', 'Service1|PASSWORD' ]
out = {};
str.forEach(function(element){
var key, value;
element = element.split('|');
key = element[0].trim();
value = element[1].trim();
out[key] = out[key] || []; // ensures we can push the value into an array
out[key].push(value);
});
console.log(out); //{ Service1: [ 'USER_ID', 'PASSWORD' ] }
We can have a simple Regex solution
var res = "Service1|USER_ID, Service1|PASSWORD".split(/[\|,]/g);
var ar1 = [], ar2 = [];
res.forEach(function(em,i){
if(i%2==0) {
if(ar1.indexOf(em.trim())<0){
ar1.push(em.trim());
}
} else {
ar2.push(em.trim());
}
});
//ar1 and ar2 will contain expected results