Convert array to array-like object [duplicate] - javascript

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 6 years ago.
I have an array, say [{ id: 'first' }, { id: 'second' }]
Are there any native methods I'm missing that will convert the array into an array-like object? I've seen plenty of answers asking about the other direction, and recommending Array.prototype.slice.call (or the newer Array.from), but I can't find anyone asking about this. For the above example, I'd want to get the following output:
{
0: { id: 'first' }
1: { id: 'second' }
}

Reducing it
var array = [{ id: 'first' }, { id: 'second' }];
var obj = array.reduce( (a,b,i) => {return a[i]=b,a},{})
console.log(obj)
Check out the documentation on Array.reduce on MDN (Mozilla Developer Network)

You could just iterate through the array and add the values to the respective index
var arr = [{ id: 'first' }, { id: 'second' }];
var set = {};
arr.forEach(function(value, index){
set[index] = value;
})
console.log(set)

Not a native method, but the following helper function should do the trick:
var arr = [{ id: 'first' }, { id: 'second' }];
function toArrayLike(arrayToConvert) {
var retVal = {};
Object.keys(arrayToConvert).forEach(function(key) {
retVal[key] = arrayToConvert[key];
});
return retVal
}
var arrayLike = toArrayLike(arr);
console.log(arrayLike);

Related

javascript/typescript get index of complex object in a multiple dimensional array

i want to get complete index of a complex object inside of a multiple dimensional array.
E.g. i have the following array.
var arr = [
{
name: "zero", children: null
},
{
name: "one", children: [
{
name: "one_zero", children: [{ name: "one_zero_zero", children: null }]
}
]
}
];
I want to get of the object with the name "one_zero_zero". It should be of indexes 1_0_0.
I hope you guys can help me with this problem.
Best regards,
var newarr =[];
var index = "";
function findmeinarr(s,arr){
for(let i in arr){
var name = "";
var flag = false;
name=arr[i].name
if(name==s){
index+=i;flag=true;
}
if(arr[i].children!=null){
newarr = arr[i].children;
index+=i+"-";
}
}
if(flag)console.log(index);
else findmeinarr(s,newarr);
}
Here is the working snippet for this :
https://codepen.io/sidhanshu28/pen/xzEyqZ
I am using recursive call here. Let me know if I can help more. Please mark it as solution, if it works for you.

How to transform an array to an object [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(7 answers)
How to convert an array of key-value tuples into an object
(14 answers)
Closed 5 years ago.
I would like to turn this:
let myArray = [ {city: "NY"}, {status: 'full'} ];
to this:
let myObj = { city: "NY", status: 'full' };
while I tried this:
let newObj = {};
for (var i = 0; i < myArray.length; i++) {
(function(x) {
newObj = Object.assign(myArray[i]);
})(i);
}
it assigns the last pair to the object
Spread the array into Object#assign:
const myArray = [ {city: "NY"}, {status: 'full'} ];
const myObj = Object.assign({}, ...myArray);
console.log(myObj);
Note: Assign into an empty object. If you omit the empty object, the 1st element of the original array will be mutated (everything will be merged into it).
You could also use Array.reduce() which will give you more fine grain control:
const myArray = [
{ city: 'NY', color: 'blue', rodents: { small: false, medium: false, large: true } },
{ status: 'full', color: 'red' },
{ sandwich: 'flavourful' },
]
// item is each object in your array
const reduced = myArray.reduce((newObj, item) => {
// existing props will be overwritten by newer object entries in the array
// this example is same as Object.assign spread with right to left precedence,
// until you want more custom logic
Object.keys(item).forEach((key) => { newObj[key] = item[key] })
return newObj
}, {})
console.log(reduced)
// you will see `red` overwrite `blue`
EDIT: after examining this answer after a year, I note that it isn't optimized at all for ability to deep clone or deep merge. I recommend studying those aspects closer and to be careful of copying or breaking references if you are working immutably.
There is no issue with this in the above example because all values are primitives.
I would tend to agree with Ori that your question seems to be about creating an indexed object which isn't usually a good plan, but if its necessary to key your object with numbers you can do it like this:
let newObj = {};
myArray.forEach((val, index) => { newObj[index] = val });
let myArray = [ {city: "NY"}, {status: 'full'} ];
let newObj = myArray.reduce((acc, curr) => {
Object.keys(curr).forEach(val => {
acc[val] = curr[val]
})
return acc
}, {})
console.log(newObj)
This syntax is supported in IE according to caniuse.com

Sorting an array object by nested values within objects - Javascript [duplicate]

This question already has answers here:
Sorted a javascript array of objects by an object property
(6 answers)
Closed 5 years ago.
I currently have an array object (not sure if this is the accurate name) that is comprised of nested key value pairs. I want to be able to sort this by the values within the nested objects.
For example:
var ObjArray = [
{ id = 1,
info = {
number = 4,
name = "foo"
}
},
{ id = 4,
info = {
number = 12,
name = "bar"
}
},
{ id = 9,
info = {
number = 2,
name = "fizz"
}
}
];
So ideally I could sort this object based on the 'number' property, and the resulting array object would have sub objects ordered by the number value within the info.
I've found a similar question (Sorting an object of nested objects in javascript (maybe using lodash?)) but doesn't account for another level of nested objects.
The sorting function needed is
ObjArray.sort((a,b) => a.info.number - b.info.number);
This will sort them ascending
For descending :
ObjArray.sort((a,b) => b.info.number - a.info.number);
var ObjArray = [{
id: 1,
info: {
number: 4,
name: "foo"
}
},
{
id: 4,
info: {
number: 12,
name: "bar"
}
},
{
id: 9,
info: {
number: 2,
name: "fizz"
}
}
];
ObjArray.sort((a,b) => a.info.number - b.info.number);
console.log(ObjArray);

Delete objects from array of objects

Object {Results:Array[3]}
Results:Array[3]
[0-2]
0:Object
id=1
name: "Rick"
upper:"0.67"
1:Object
id=2
name:'david'
upper:"0.46"
2:Object
id=3
name:'ashley'
upper:null
I have this array of objects as shown above. and a variable named delete_id
delete_id = 1,2
So this indicates objects with id 1 and 2. It should delete the objects in the array of objects and give the final result as follows:
Object {Results:Array[1]}
Results:Array[3]
[0]
0:Object
id=3
name:'ashley'
upper:null
Can someone let me know how to achieve this. I tried to use this below function. It only deletes the first value in variale delete_id. i.e. id with 1 is deleted. similary if we have delete_id = 2,3 then it only deletes 2. I want to delete 2 and 3 both...
function removeID(delete_id) {
tabledata = tabledata.filter(function (obj) {
return delete_id.indexOf(obj.id);
});
You can use .split() and .map() to transform your delete_id string into an array of numeric IDs. Then, you can use .filter() to do the cleanup.
var players = [
{
id: 1,
name: "Rick",
upper: "0.67"
},{
id: 2,
name: "david",
upper: "0.46"
},{
id: 3,
name: "ashley",
upper: null
}
];
var delete_id = "1,2";
var exclude = delete_id.split(',').map(Number);
players = players.filter(function(player) {
return exclude.indexOf(player.id) == -1;
});
console.log(players);
function findObj(array,value,key) {
var result = array.filter(function (obj) {
if (obj[key] === value || obj[key] == value)
return obj;
});
return result;
};
First find the object from the
array(tabledata),value=1(delete_id),key=the key in json(id)
var selectedObj=findObj(tabledata,delete_id,'id');
get index of that object in the array
var index=tabledata.indexOf(selectedObj[0]);
delete its index
tabledata.splice(index,1);
The code runs if you change the removeID code to see if the index is equal to -1
function removeID(delete_id) {
tabledata = tabledata.filter(function(obj) {
return delete_id.indexOf(obj.id)===-1; //added === -1 here
});
}
var tabledata = [{
id: 1,
name: "Rick",
upper: "0.67"
}, {
id: 2,
name: 'david',
upper: "0.46"
}, {
id: 3,
name: 'ashley',
upper: null
}];
var ids = [1,2]; //defined it as an array (not sure if you did)
removeID(ids);
console.log(tabledata);
I assume that delete_id is an integer array. In that case you can filter to exclude provided ids with code below.
It'll check if obj.id is not in delete_id, then obj will be included in a new filtered array. Also it will leave tabledata intact.
var filtered = tabledata.filter(function(obj) {
return !(obj.id in delete_id)
})

Filter response object based on an array of whitelisted ids

How to Filter a response object based on an array of whitelisted ids?
I've a working version but i don't like the nested forEach here and i wonder if there is a way to improve it?!
function WhitelistCtrl($scope) {
var visible = [];
var whitelist = [123, 456]; // items to be visible
var response = [{
id: 123,
name: 'my object #1'
}, {
id: 456,
name: 'my object #2'
}, {
id: 789,
name: 'my object #3'
}];
angular.forEach(whitelist, function (id) {
angular.forEach(response, function (item) {
if (id === item.id) {
visible.push(item);
}
});
});
}
Here is a JSFiddle to play with: http://jsfiddle.net/gearsdigital/rv6vq2L7/
I'm not much familiar with Anglar ForEeach but you can achive this using native javascript filter like bellow
visible = response.filter(function(item){
return (whitelist.indexOf(item.id) > -1);
})
DEMO
NOTE:- IE8 doesn't supports .filter.

Categories