Convert nested array to object - javascript

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

Related

Get the first and last item in an Array - JS

I am trying to get the first and last item in array and display them in an object.
What i did is that I use the first and last function and then assign the first item as the key and the last item as the value.
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray.first;
var lastItem = myArray.last;
var objOutput = {
firstItem : lastItem
};
}
var display = transformFirstAndLast(myArray);
console.log(display);
however this one gets me into trouble. It says undefined. Any idea why is that?
I've modified your code :
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];
var objOutput = {
first : firstItem,
last : lastItem
};
return objOutput;
}
var display = firstAndLast(myArray);
console.log(display);
UPDATE: New Modification
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray[0];
var lastItem = myArray[myArray.length-1];
var objOutput = {};
objOutput[firstItem]=lastItem
return objOutput;
}
var display = firstAndLast(myArray);
console.log(display);
With ES6 and destructuring:
const myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
const { 0: first, length, [length -1]: last } = myArray //getting first and last el from array
const obj = { first, last }
console.log(obj) // { first: "Rodel", last: "Betus" }
ES6
var objOutput = { [myArray[0]]: [...myArray].pop() }
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
var objOutput = { [myArray[0]]: [...myArray].pop() }
console.log(objOutput);
As of 2021, you can use Array.prototype.at()
let colors = ['red', 'green', 'blue']
let first = colors.at(0) // red
let last = colors.at(-1) // blue
To read more about Array.prototype.at()
I prefer using a simple array filter:
const myArray = ['one', 2, 3, 4, 5];
const filterFirstLast = (e, i, a) => i === 0 || i === a.length - 1;
const [ first, last ] = myArray.filter(filterFirstLast);
console.log(first, last); // outputs: 'one', 5
// dealing with insufficient input is another topic (input array length < 2)
console.log(['one'].filter(filterFirstLast )); // outputs: ['one']
console.log([].filter(filterFirstLast )); // outputs: []
transforming to something else is as easy
const obj = { [first]: last }; // will be: { one: 5 }, but never { one: "one" }
// OR, if you allow ['one'] to apply for both, if last is nullish (e.g. undefined, null, ""):
const obj = { [first]: last || first }; // will be: { one: 5 }, can be { one: "one" }
Another variation of roli answer
function firstAndLast(array) {
return { [[...array].shift()]: [...array].pop() };
}
To make your first and last properties work as you want, define them as properties with "getters" on the array prototype.
(You also have an inconsistency between firstAndLastArray and transformFirstAndLast, which needed to be fixed.)
Returning {firstName: lastName} will not do what you presumably want, since it will yield the key firstName. To use the actual first name as the key, use computed property names ({[firstName]: lastName}).
Object.defineProperties(Array.prototype, {
first: { get() { return this[0]; }},
last: { get() { return this[this.length - 1]; }}
});
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(array) {
var firstItem = myArray.first;
var lastItem = myArray.last;
return {[firstItem]: lastItem};
}
var display = firstAndLast(myArray);
console.log(display);
Or, much more simply, just
function firstAndLast(array) {
return {[array[0]]: array[array.length - 1]};
}
If you don't want to, or cannot, use computed property names, then
function firstAndLast(array) {
var result = {};
result[array[0]] = array[array.length - 1];
return result;
}
Do like this :-
var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
function firstAndLast(myArr) {
var firstItem = myArr[0];
var lastItem = myArr[myArr.length - 1];
var objOutput = {};
objOutput[firstItem] = lastItem;
return objOutput;
}
var display = firstAndLast(myArray);
console.log(display);
well, I have another idea... for ex.:
const all = ['food', 'clean', 'cat', 'shower', 'work out']
console.log(`you have ${all.length} all!`)
console.log(`Todo: ${all[0]}`)
console.log(`Todo: ${all[all.length - 1]}`)
try this to find out first and last value of an array
var array = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
let {0 : a ,[array.length - 1] : b} = array;
var objOutput = {
first : a,
last:b
};
console.log(objOutput)
In Array :- Check first and last element in array are same or not..
function hasSame(arr1, arr2) {
for(i=0; i <arr1.length ; i++) {
for(j=0; j <arr2.length ; j++) {
if(arr1[0] === arr2[0] && arr1[2] === arr2[2]) {
return true
} else
return false;
}
}
}
console.log(hasSame(
["white bread", "lettuce", "toast"],
["white bread", "tomato", "toast"]
))

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>");

Javascript transform array into grouped object by value

I have an array:
["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"]
The array can have different sets of cars, and I want to turn it into something like this:
[{
car1: ["car1-coupe"]
},{
car2: ["car2-convertible", "car2-hatchback", "car2-estate"]
},{
car3: ["car3-hatchback", "car3-estate"]
}]
How can I do this in JavaScript or Underscore?
So, assuming an array like this:
var a = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
You can do this:
var b = a.reduce(function(prev, curr){
var car = curr.split('-')[0]; // "get" the current car
prev[car] = prev[car] || []; // Initialize the array for the current car, if necessary.
prev[car].push(curr); // Add the current item to the array.
return prev;
}, {});
This will return the following object:
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
var array = ["car1-coupe", "car2-convertible", "car2-hatchback", "car2-estate", "car3-hatchback", "car3-estate"];
var result = {};
for (var i = 0; i < array.length; i++) {
var key = array[i].split('-')[0]; // The car we're interested in
if (result[key]) { // Check if this car has already been initialized
result[key].push(array[i]); //add this model to the list
} else {
result[key] = [array[i]]; // initialize the array with the first value
}
}
console.log(result);
/*will return :
{
car1: ["car1-coupe"],
car2: ["car2-convertible", "car2-hatchback", "car2-estate"],
car3: ["car3-hatchback", "car3-estate"]
}
*/
var myObj = {}, myArr = [];
for( var i = 0; i < arr.length; i+=1) {
var key = arr[i].split("-")[0];
myObj = {};
myObj[key] = [];
for( var j = i; j < arr.length; j+=1 ) {
if( key === arr[j].split("-")[0])
myObj[key].push(arr[j]);
}
myArr.push(myObj);
}
I think this can be done simply with this way. One loop to get the key and another inner loop to get all values of this key.

Trying to loop through arrays containing arrays containing objects, to match data

I'm tryign to write code that will loop through an array "productsArray" and match it against my productPropertyArray to pull matching information.
however productsArray is an array in an array that contains an object with the data. My Question is how can I loop through both arrays and then return the matching data.
Current function:
var pList = productsArray
if (productPropertyArray.length === 0 || productsArray.length === 0) return [];
for (var i = 0; i < pList.length; i++) {
for (var j = 0; j < pList[i].length; j++) {
if (pList[i][j] === productPropertyArray) {
return productPropertyArray;
} else {
continue;
}
}
}
return [];
};
example of pList:
productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": 1}],
[{"sellAlone": false,"test": 1}]
];
example of productPropertyArray: (its an argument thats replaced by the following)
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
productPropertyArray is just an argument in the function which is replaced by productSKUArray The setup goes like this: function(productProperty, productPropertyArray, productsArray) {
productProperty is just a string that contains sku or productID
any ideas are appreciated. thanks.
Check this out:
http://jsfiddle.net/v9d7bjms/2/
function find() {
var productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": "00544MF24F575"}],
[{"sellAlone": false,"test": 1}]
],
pList = productsArray,
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
// All arrays matching your productsSKUArray
var findings = productsArray.filter(function (productProperty) {
// .some returns true after finding first matching element (and breaks the loop)
return productProperty.some(function (obj) {
var keys = Object.keys(obj);
// We need to get all the "values" from object so we interate over
// the keys and check if any value matches something from productSKUArray
return keys.some(function (key) {
// Check if value exists in productsSKUArray
return productSKUArray.indexOf(obj[key]) > -1;
});
});
});
return findings;
}
console.log(find());
.filter will return all arrays containing objects with values from productSKUArray.
See Array.prototype.filter, Array.prototype.some and Array.prototype.indexOf for method reference.
The inner if needs to refer to pList[i][j].
This will output [{sku: "131674"}, {sku: "84172"}].
var matchingData = [];
for(var productProperties in productsArray){
var pp = productsArray[productProperties];
for(var property in pp) {
var p = pp[property];
for(var propertyName in p){
var propertyValue = p[propertyName];
for(var i in productSKUArray){
if(propertyValue == productSKUArray[i]){
matchingData.push(p);
break;
}
}
}
}
}
but this is just the brute force solution.

An array converting question

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

Categories