I have weird object:
{"Cats":10,"Dogs":815,"Fishes":2}
How can I get full value from each piece of data
var t = {"Cats":10,"Dogs":815,"Fishes":2};
var keys = [];
for (var key in t) {
if (t.hasOwnProperty(key)) {
console.log(key)
}
}
I'm getting only the names without number
I can use JSON.stringify and then manipulate that object but maybe there is other way?
Probably I missing something?
the for...in statement iterate over the property names get the value by property name.
var t = {"Cats":10,"Dogs":815,"Fishes":2};
var keys = [];
for (var key in t) {
if (t.hasOwnProperty(key)) {
console.log(key, t[key])
}
}
If you would like to generate an array of values then use Object.keys and Array#map methods.
var t = { "Cats": 10, "Dogs": 815, "Fishes": 2};
var keys = Object.keys(t);
var values = keys.map(function(key) {
return t[key];
});
console.log(keys, values);
var t = {"Cats":10,"Dogs":815,"Fishes":2};
var keys = [];
for (var key in t) {
if (t.hasOwnProperty(key)) {
console.log(key, t[key])
}
}
You could get the own properties first with Object.keys and iterate then.
var t = { Cats: 10, Dogs: 815, Fishes: 2 },
keys = Object.keys(t);
keys.forEach(function (key) {
console.log(key, t[key]);
});
var t = {"Cats":10,"Dogs":815,"Fishes":2};
for (var key in t)
{
console.log(key, t[key]);
}
Related
I have several objects like this:
{'id[0]': 2}
{'url[0]': 11}
{'id[1]': 3}
{'url[1]': 14}
And I want to get something like this:
[{id:2, url:11}, {id:3, url:14}]
Also I have lodash in my project. Maybe lodash have some method for this?
You could use a regular expression for the keys and create a new object if necessary. Then assign the value to the key.
var data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }],
result = [];
data.forEach(function (a) {
Object.keys(a).forEach(function (k) {
var keys = k.match(/^([^\[]+)\[(\d+)\]$/);
if (keys.length === 3) {
result[keys[2]] = result[keys[2]] || {};
result[keys[2]][keys[1]] = a[k];
}
});
});
console.log(result);
This is an ES6 solution based on #NinaScholz solution.
I assume that the objects have only one property each, like the ones presented in the question.
Combine the array of objects to one large object using Object#assign, and convert to entries with Object.entries.
Iterate the array using Array#reduce.
Extract the original key an value from each entry using array
destructuring.
Extract the wanted key and index using a regex and array
destructuring.
Then create/update the new object at the index using object spread.
const data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }];
// combine to one object, and convert to entries
const result = Object.entries(Object.assign({}, ...data))
// extract the original key and value
.reduce((r, [k, value]) => {
// extract the key and index while ignoring the full match
const [, key, index] = k.match(/^([^\[]+)\[(\d+)\]$/);
// create/update the object at the index
r[index] = {...(r[index] || {}), [key]: value };
return r;
}, []);
console.log(result);
var arr = [{'id[0]': 2},
{'url[0]': 11},
{'id[1]': 3},
{'url[1]': 14}];
var result = [];
arr.forEach(function(e, i, a){
var index = +Object.keys(e)[0].split('[')[1].split(']')[0];//get the number inside []
result[index] = result[index] || {}; //if item is undefined make it empty object
result[index][Object.keys(e)[0].split('[')[0]] = e[Object.keys(e)[0]];//add item to object
})
console.log(result);
You can use for loop, .filter(), RegExp constructor with parameter "\["+i+"\]" where i is current index, Object.keys(), .reduce(), .replace() with RegExp /\[\d+\]/
var obj = [{
"id[0]": 2
}, {
"url[0]": 11
}, {
"id[1]": 3
}, {
"url[1]": 14
}];
var res = [];
for (var i = 0; i < obj.length / 2; i++) {
res[i] = obj.filter(function(o) {
return new RegExp("\[" + i + "\]").test(Object.keys(o))
})
.reduce(function(obj, o) {
var key = Object.keys(o).pop();
obj[key.replace(/\[\d+\]/, "")] = o[key];
return obj
}, {})
}
console.log(res);
I am trying to sort my object keys.
But when I'm printing my object, it always print bb first. Can anyone explain this?
It should print aa first ? I already sorted my keys.
My first key should be aa and then second should be bb.
Here is my code
var data = {
bb:"bb",
aa:"cc"
};
Object
.keys(data)
.sort();
console.log(data)
DEMO
Two things:
objects in JS have no order of elements, like arrays do
Object.keys returns an array of object keys, it does not modify the object itself, see the following example:
var data={bb:"bb",aa:"cc"};
var arr = Object.keys(data);
arr.sort();
console.log(arr); // the array IS modified,
// but it has nothing to do with the original object
try this
var data={bb:"bb",aa:"cc"};
var keys = Object.keys(data);
keys.sort();
var obj = {};
for(i = 0; i < keys.length; i++){
obj[keys[i]] = data[keys[i]];
}
console.log(obj);
There is not any method for sorting object keys in JavaScript but you can do this by a object prototype like this.
Object.prototype.sortKeys = function () {
var sorted = {},
key, a = [];
for (key in this) {
if (this.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = this[a[key]];
}
return sorted;
}
var data = {bb: "bb", aa :"cc"};
alert(JSON.stringify(data.sortKeys())); // Returns sorted object data by their keys
I have an object like this:
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1}
I want to change it into an object like this:
{
"prop": {
"health": 1,
"cost":1,
"time":1
}
}
Here's my code:
_.each(data, function (value, key) {
var split = key.split('.')
if (split.length > 1) {
data[split[0]] = data[split[0]] || {}
data[split[0]][split[1]] = value
delete data[key]
}
})
But this only works for 1 level of nesting. How would you write it to ensure it works for as deeply nested properties as you need?
You can use a combination of _.transform and _.set, for example
data = _.transform(data, function(transformed, val, key) {
_.set(transformed, key, val);
});
Results in
{"prop":{"health":1,"cost":1,"time":1}}
Without a library it would be something like this:
(function(){
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1, "prop.test.fun" : 1, "prop.test.sun" : 1};
var obj = {}; //will hold the object all parsed out
Object.keys(data).forEach( function (key) { //loop through the keys in the object
var val = data[key]; //grab the value of this key
var step = obj; //reference the object that holds the values
key.split(".").forEach(function(part, index, arr){ //split the parts and loop
if(index===arr.length-1){ //If we are at the last index, than we set the value
step[part] = val;
} else if(step[part]===undefined) { //If we have not seen this key before, create an object
step[part] = {};
}
step = step[part]; //Step up the object we are referencing
});
} );
console.log(obj);
}());
Or the double reduce loop
(function(){
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1, "prop.test.fun" : 1, "prop.test.sun" : 1};
var result = Object.keys(data).reduce( function (obj, key) { //loop through the keys in the object
var val = data[key]; //grab the value of this key
key.split(".").reduce(function(step, part, index, arr){ //split the parts and loop
if(index===arr.length-1){ //If we are at the last index, than we set the value
step[part] = val;
} else if(step[part]===undefined) { //If we have not seen this key before, create an object
step[part] = {};
}
return step[part]; //Step up the object we are referencing
}, obj);
return obj;
}, {});
console.log(result);
}());
Depending on a number of factors (e.g. if the original object always has keys you want to delete, etc.) you may be able to use _.set:
var data = {"prop.health": 1, "prop.cost":1, "prop.time":1};
_.each(data, function (value, key) {
delete data[key];
_.set(data, key, value);
});
_.set will create the path if it doesn't exist. The above results in:
{"prop":{"health":1,"cost":1,"time":1}}
And {"prop.health": 1, "prop.cost.food":1, "prop.time":1} will result in:
{"prop":{"health":1,"cost":{"food":1},"time":1}}
I have an array from json like this:
{"1001":"Account1","1002":"Account2","1003":"Account3"}
and i need convert it to key value format:
[{id:"1001",name:"Account1"},
{id:"1002",name:"Account2"},
{id:"1003",name:"Account3"}]
To do this i wrote this function:
function arrayToMultiArray(list) {
var matrix = [], i;
i = -1;
for (var key in list) {
i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});
}
return matrix;
}
but the generated array has brackets for each array
[[{id:"1001",name:"Account1"}],
[{id:"1002",name:"Account2"}],
[{id:"1003",name:"Account3"}]]
How can i remove brackets of internal arrays?
You added array in array.
Just change
i++;
matrix[i] = [];
matrix[i].push({"id":key, "name":list[key]});
to
matrix.push({"id":key, "name":list[key]});
you are creating a multidimensional array.
remove this
i++;
matrix[i] = [];
and do this directly
matrix.push({"id":key, "name":list[key]});
You could do the same with Object.keys and Array.prototype.map
var obj = {"1001":"Account1","1002":"Account2","1003":"Account3"};
var arr = Object.keys(obj).map(function(key) {
return { id : key, name : obj[key] }
});
console.log(arr);
If I have an object like:
var o = {a:1,b:2,c:3};
I want to get:
['a','b','c'];
I want to use for (var i in o) because this will include properties from prototype chain. I could have used Object.keys(o) if I didn't need properties from prototype chain.
I was thinking I could use some of Array.prototype.* methods here. Like map but this is too advance for me.
I can make a string from loop and do split. But is there more efficient and professional level of doing this?
You can use the keys method in lodash, https://lodash.com/docs#keys
You could also use the following code
var arr = [];
var o = {a:1,b:2}
for(k in o) { arr.push(k); }
Here is another version which goes deep into the object
function getKeys(o) { var arr = []; for(k in o) { arr.push(k); if(typeof(o[k]) === 'object') { arr.push(getKeys(o[k])); }} return arr; }
If you have an object like {a:1,b:2, c: {d:1, e:2}} you would get the return as ['a','b','c',['d','e']]
A completely flat version would be this one
function getKeys(o) { var arr = []; for(k in o) { arr.push(k); if(typeof(o[k]) === 'object') { for(j of getKeys(o[k])){ arr.push(j); } }} return arr; }
If you have the following hash
var o = {a:1,b:2,c:3};
Create a new empty array for storing the keys
var array_keys = new Array();
Then use a for loop to push the keys into the array
for (var key in o) {
array_keys.push(key);
}
You can then run alert(array_keys)
This is a solution that avoids the for...in that you mentioned. However, I think the for...in solution is much more elegant.
This will walk the prototype chain and return all properties as a recursive function. As well as remove all duplicates.
function getKeys(obj) {
var keys = Object.keys(obj);
var parent = Object.getPrototypeOf(obj);
if (!parent) {
return keys;
}
return keys.concat(getKeys(parent))
.filter(function (item, index, col) {
return col.indexOf(item) === index;
});
}
var a = { a: 1, b: 2 };
var b = Object.create(a);
b.a = 2;
b.c = 3;
var c = Object.create(b);
console.log(getKeys(c));