An array converting question - javascript

I have an array below,
var array = {
"Id":[1,2,3],
"Name":["one","two","five"],
"row":[8,9,7]
}
but I want to transform it into
var array2 =
{"data":
[
{"Id":1,"Name":"one","Row:8"},
{"Id":2,"Name":"two","Row:9"},
{"Id":3,"Name":"five","Row:7"},
]
}
Is this possible?

This should do it:
// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
// Note that array.Id = [1,2,3] does not result in corresponding keys
// array.Id[0] corresponds to value 1!
array2.data.push({
Id: array.Id[i],
Name: array.Name[i],
Row: array.Row[i]
});
}

var array2 = {data: []};
for (i in array.Id) {
array2.data.push({
Id: array.Id[i],
Name: array.Name[i],
row: array.row[i]
});
}
Didn't test it

it's not an array. it's an object.
var myArr = [1,2,3]; //Array definition
var myObj = {test:"1",test2:"2"}; //Object Definition
var array = [1,[1,2,3]]; // multidimensional array

Related

Javascript two array merge( key and value)

I have two array. I want to merge this two arrays into one array. One array consisting keys and another one values.My array looks like
productId = [8,7,9];//Key Element
quantity = ["5","1","3"];//Value Element
//expected new array
newarray = {
"8": 5,
"7": 1,
"9": 3
}
I already tried to merge these arrays, in this way
var newArray = {};
for(var i=0; i< productId.length; i++){
newArray[productId[i]] = quantity [i];
}
console.log(newArray);
It returns
Object [ <7 empty slots>, "5", "1", "3" ]
You are working in firefox so you may get this type of issue because the problem might be caused at how Firefox' console.log has interpreted the input object.
Please look here
Empty slots in JavaScript objects?
Try this
var productId = [8,7,9];
var quantity = ["5","1","3"];
var newarray = {};
productId.forEach((key, i) => newarray[key] = quantity[i]);
console.log(newarray);
Try the following:
var productId = [8,7,9];//Key Element
var quantity = ["5","1","3"];//Value Element
var obj = {};
var i = 0;
for(var k of productId) {
obj[k] = parseInt(quantity[i]);
i++;
}
console.log(obj);
Your new "array" is not an Array but an Object.
You can iterate on one of the arrays using Array.reduce to construct the object.
Something like that:
const arr1 = ['8', '2', '4'];
const arr2 = ['28', '12', '45'];
const result = arr1.reduce((obj, currentItem, index) => {
obj[currentItem] = arr2[index];
return obj;
}, {});
console.log(result);

Sorting key value pair on basis of another array

I have key value pairs like :
var x={1:Car,
2: Cycle,
3:John
}
This is response coming from JSON.[Object object]
I have array like :var arr=[1,3,2]
I want to sort x as per arr .
order should be : {1:Car,3:John,2:Cycle}
In javascript how to achieve this.
You don't need to sort them, just make a new empty array and populate it by getting the values of arr and using them as the index of x.
var x = {
1: 'Car',
2: 'Cycle',
3: 'John'
};
var arr = [1, 3, 2];
var output = [];
arr.forEach(function(item){
output.push(x[item]);
});
console.log(output);
Fiddle.
var order = function(obj, arr) {
var temp = {};
for (var i = 0; i < arr.length; i++) {
temp[i] = obj[arr[i]];
}
return temp;
}
var x = {
1: "Car",
2: "Cycle",
3: "John"
}
var arr = [1, 3, 2]
x = order(x, arr);
console.log(x);

how to make array of object using an array?

I have one array
var ar=['aa','cc','po']
I want to push objects in new array after checking the value of given array .In other words
I have these given conditions
var ar=['aa','cc','po']
var arr =[{name:"po"},{name:'aa'},{name:'cc'}];
Expected Output in new Array
[{name:'aa'},{name:'cc'},{name:"po"}]
As "aa" in in 0 index then I added object whose name property aa.
I try like this .but I used two for look .is there any simple way to do this
FIDDLE
var newArr=[];
for(var i=0;i<ar.length ;i++){
var text =ar[i];
for(var j=0;j<arr.length ;j++){
var obj =arr[j];
console.log(obj.name);
/*if(obj.name===text){
newArr.push(obj);
}*/
}
}
console.log(newArr);
This is a proposal in two part, first build an object with the reference to the items of arr and the create a new array with the given items of ar.
var ar = ['aa', 'cc', 'po'],
arr = [{ name: "po" }, { name: 'aa' }, { name: 'cc' }],
object = Object.create(null),
result = [];
arr.forEach(function (a) {
object[a.name] = a;
});
ar.forEach(function (a) {
object[a] && result.push(object[a]);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Using forEach iterator and generate object reference based on name and then generate result array using map()
var ar = ['aa', 'cc', 'po']
var arr = [{
name: "po"
}, {
name: 'aa'
}, {
name: 'cc'
}];
var ref = {};
// generating object reference with name property
arr.forEach(function(v) {
ref[v.name] = v;
});
// generating result array
// or you can use forEach as #NinaScholz answer
var res = ar.map(function(v) {
return ref[v];
}).filter(function(v) { // use filter to avoid null values , in case of missing elements
return v != null;
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
Try this:
function convert(source) {
var
obj = [],
i;
for (i = 0; i < source.length; ++i) {
obj.push({name: source[i]});
}
return obj;
}
convert(['aa', 'bb', 'cc']); // [{name:'aa'},{name:'bb'},{name:'cc'}]
This would work if you want to assign values from array in sequence:
var ar=['aa','cc','po']
var arr =[{name:"po"},{name:'aa'},{name:'cc'}];
arr.map(function(obj,key){
obj.name = ar[key];
});
console.log(arr);
Do like this
var ar = ['aa', 'cc', 'po']
var arr = [{ name: "po"}, { name: 'aa'}, { name: 'cc'}];
$.each(ar, function(i, v) {
arr[i].name = v;
});
console.log(arr)
Fiddle
var array=['a','b','c'];
var arrayObj=[];
for(var i=0;i<array.length;i++){
var obj={};
obj.name=array[i];
arrayObj.push(obj);
}
console.log(JSON.stringify(arrayObj));
Output:
[{"name":"a"},{"name":"b"},{"name":"c"}]
I guess this is one very functional way of doing this job with no more than an assignment line. However Anoop Joshi's answer is more elegant provided that the ar array is shorter than equal to in length to the arr array.
var arr = ['aa','cc','po'],
ar = [{name:"po"},{name:'aa'},{name:'cc'}],
res = arr.map(e => ar[ar.findIndex(f => f.name == e)]);
document.write("<pre>" + JSON.stringify(res) + "</pre>");

Push from one array to another by reference

Given this fiddle, does anyone have a suggestion as to how I might update the indices of array1? Or more to the point, any idea how to make the indices of array2 references to indices of array1?
http://jsfiddle.net/y8rs56r3/
var array1 = [
{num:"one"},
{num:"two"},
{num:"three"}
];
var array2 = [];
var i = array1.length;
while(i--){
if(i!=1)array2.push(array1[i]);
}
array2[0].num = "one updated";
console.log(array2);
console.log(array1);
Obviously, in this codeblock, array1[0] is not updated.
since your array is set of objects try like this:
var array1 = [
{num:"one"},
{num:"two"},
{num:"three"}
];
var array2 = [];
for(x in array1){
array2.push(array1[x]);
}
array2[0].num = "one updated";
console.log(array2);//output [Object { num="one updated"}, Object { num="two"}, Object { num="three"}]
console.log(array1);// output [Object { num="one updated"}, Object { num="two"}, Object { num="three"}]

Convert nested array to object

I am looking for a solution, to push/convert array items into a object back, without using keys?
function pleaseBuy(){
var args = arguments;
for(var i = 0; i < arguments[0].length; ++i) {
args += args[i];
};
};
function getList(){
return ["pepsi","cola","7up"];
}
var list = ({ favorite: "drpepper"}, getList())
pleaseBuy(list)
Expected result:
args = ({ favorite: "drpepper"}, "pepsi", "cola", "7up")
No need for the pleaseBuy function, I'd say:
function getList(){
return ["pepsi","cola","7up"];
}
var list = getList().concat( { favorite: "drpepper" } );
// ^ NB should be :
// or favorite first
var list = [{ favorite: "drpepper" }].concat(getList());
/*
list now contains:
['pepsi, 'cola','7up',{ favorite: "drpepper" }]
*/
An object allways contains key-value pairs. If you want to convert an array to an object, you'll thus have to assign keys and values. For example:
var arr = [1,2,3,4,'some'], arr2Obj = {};
for (var i=0;i<arr.length;i=i+1){
arr2Obj[arr[i]] = i;
}
/*
arr2Obj now contains:
{
1: 0,
2: 1,
3: 2,
4: 3,
some: 4
}
*/
Other example:
var arr = [1,2,3,4,'some'], arr2Numbers = {};
for (var i=0;i<arr.length;i=i+1){
arr2Numbers[arr[i]] = !isNaN(Number(arr[i]));
}
/*
arr2Numbers now contains:
{
1: true,
2: true,
3: true,
4: true,
some: false
}
*/
Do you mean the javascript push function?
Use .unshift() docs to prepend to an array.
var list = getList();
list.unshift( { favorite="drpepper"});
// [{ favorite="drpepper"}, "pepsi", "cola", "7up"]
Demo at http://jsfiddle.net/Ds9y5/
Try this:
var array = ["pepsi","cola","7up"];
array.push({ favorite: "drpepper"});
Or
var array2 = ["pepsi","cola","7up"];
var array = [{favorite: "drpepper"}];
for(var ctr = 0 ; ctr < array2.length ; ctr++){
array.push(array2[ctr]);
}
var s = getList();
s.unshift({ favorite : "drpepper"}); // at the first place in array
s.push({ favorite : "drpepper"}); // at the last place in array
alert(s);
JavaScript push() Method
JavaScript unshift() Method

Categories