I have tried to take the particular array value of key from a JSON object and store that in an array which will be look like this.
Example:
var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
"2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
"3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
}
and so on like this
Now i need to take the value of key "box" and store in an array.
var list = []
list = [[0.2,0.3,0.4,0.5],[0.12,0.23,0.45,0.56],[0.52,0.83,0.34,0.59]]
But, i tried multiple ways to store the array inside the array, but i could able to get like this when i printed the list
list = 0.2,0.3,0.4,0.5,0.12,0.23,0.45,0.56,0.52,0.83,0.34,0.59
You can use Object.keys (which returns an array of all key of your json) in combination with array’s map to transform your json into a new array:
const boxes = Object.keys(obj).map(key => obj[key].box)
You can also use Object.values, which is actually nicer in your case:
const boxes = Object.values(obj).map(value => value.box)
How it works
Object.keys return an array:
Object.keys(obj) // ["1", "2", "3"]
then you can map over them to get the value of each item:
Object.keys(obj).map(key => obj[key]) // [{box: [...]}, {box: [...]}, {box: [...]}]
then in array.map's callback, you can simply only return the box value:
Object.keys(obj).map(key => obj[key].box) // [[...], [...], [...]]
Without Object.keys()
function getBoxes (object) {
var boxes = [];
for (var key in object) {
if (!object.hasOwnProperty(key)) continue;
boxes.push(object[key].box);
}
return boxes;
}
console.log(getBoxes(obj))
for...in can loop through object's properties, but it'll also loop over inherited properties, therefore we need to guard the loop with object.hasOwnProperty(key).
Object.keys(): Return an array of all enumerable property names of an object
Object.values(): Return an array of all enumerable values of an object
array.map(): Return a new array with each item of the original array transformed in a given callback function
array.slice(): Return a shallow copy of the original array
Try this:
Object.values(obj).map(x=>x.box);
var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
"2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
"3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
}
let list = Object.values(obj).map(x=>x.box);
console.log(JSON.stringify(list))
The Object.values returns array of obj values, then we use map to iterate over that values (we use arrow function) and create new array with box values.
Check next example:
1) First, use Object.keys() to get an array with the keys of the object.
2) Second, loop on every key and access the box property of the object associated with every key, then push this box property on a new array.
var obj = {
"1": {"class":2, "percent":0.99, "box":[0.2,0.3,0.4,0.5]},
"2": {"class":2, "percent":0.99, "box":[0.12,0.23,0.45,0.56]},
"3": {"class":2, "percent":0.99, "box":[0.52,0.83,0.34,0.59]}
};
var arrayOfArrays = [];
Object.keys(obj).forEach(function(k){
arrayOfArrays.push(obj[k].box);
});
console.log(arrayOfArrays);
Here is (just for fun) another alternative using the reduce() method:
var obj = {
"1": {"class":2, "percent":0.99, "box":[0.2,0.3,0.4,0.5]},
"2": {"class":2, "percent":0.99, "box":[0.12,0.23,0.45,0.56]},
"3": {"class":2, "percent":0.99, "box":[0.52,0.83,0.34,0.59]}
};
const reducer = (accumulator, currVal) => {
accumulator.push(currVal.box);
return accumulator;
};
arrayOfArrays = Object.values(obj).reduce(reducer, []);
console.log(arrayOfArrays);
Related
For Example :
I have an object and in that object, I have values in the array. I want to return the array which contains the key which contains the value passing as a variable.
function getValues(val , object){
return []; // return [b,c] because xyz are present in both
}
var object = {
"a" : ["abc", "cde","efg"],
"b" : ["asdf","asee","xyz"],
"c" : ["asaw","wewe","xyz"]
getValues("xyz", object);
}```
There are various ways to approach this.
One could be using Object's native functions:
function getValues(str, obj) {
return Object
// returns the entries pairs in a array of [key, value]
.entries(obj)
// from the array it searches the value for the string inputted and maps it back
.map(([key, array]) => array.includes(str) ? key : undefined)
// simply remove the undefined returned values from map()
.filter((value) => value);
};
This could have been done with reduce() as well but I found it easier to explain this way.
Another approach is using a for loop to iterate over the keys of the object:
function getValues(str, obj) {
let arr = [];
// Iterates through the object selecting its keys
for (let key in obj) {
// If the array of the current key has the string in it, includes in the array
if (obj[key].includes(str)) {
arr.push(key)
}
}
return arr;
}
I have an array of objects:
boxes= [{"itemsId":19,"quantity":0},{"itemsId":1053,"quantity":1},{"itemsId":1056,"quantity":1}];
How to pair values of objects from array?
Here's what I'd like boxes to look like:
boxes= [{"itemsId":quantity},{"itemsId":quantity},{"itemsId":quantity}];
ie.
boxes= [{"19":0},{"1053":1},{"1056":1}];
You can try with Array.prototype.map():
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
In each iteration set the value of itemsId as the key and the value of quantity as the value for that key.
var boxes= [{"itemsId":19,"quantity":0},{"itemsId":1053,"quantity":1},{"itemsId":1056,"quantity":1}];
boxes = boxes.map(i => ({[i.itemsId]:i.quantity}));
console.log(boxes);
You can use map to return an array and inside the callback return an object.Use square notation to create the object key. Since object key is unique the new value will overwrite old value inside an object
let boxes = [{
"itemsId": 19,
"quantity": 0
}, {
"itemsId": 1053,
"quantity": 1
}, {
"itemsId": 1056,
"quantity": 1
}];
let newData = boxes.map(function(elem) {
return {
[elem.itemsId]: elem.quantity
}
});
console.log(newData)
Using map()
var boxes = [{"itemsId":19,"quantity":0},{"itemsId":1053,"quantity":1},{"itemsId":1056,"quantity":1}];
var result = boxes.map(({itemsId, quantity}) => ({[itemsId]: quantity}))
console.log(result)
is there a "Nice" way to get all the values out of a json object (I don't care about the keys) - just get the values into array,
without using a loop ?
(lang is Javascript)
It depends on how you define "loop".
You can extract the properties with Object.keys and then map them to their values.
… it's still essentially a loop under the hood though.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
console.log(values);
With weaker browser support you could use the values method.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.values(obj);
console.log(values);
I think you are looking for Object.values() function, just pass the object to the values method of Object as first param. That's it!
Object.values({something: 'lol'});
> ["lol"]
Recursively extract as text
Yes, this is a loop but the underlying methods you are calling such as Object.values or arr.map are still loops. I found this useful for extracting text out of a json object for full text search in particular and thought it useful as I came here initially needing this but the answers only touched the surface as json is recursive in nature.
function textFromJson(json) {
if (json === null || json === undefined) {
return '';
}
if (!Array.isArray(json) && !Object.getPrototypeOf(json).isPrototypeOf(Object)) {
return '' + json;
}
const obj = {};
for (const key of Object.keys(json)) {
obj[key] = textFromJson(json[key]);
}
return Object.values(obj).join(' ');
}
With ES2017 you have Object.values(). You can polyfill it also.
Only you need is transform JSON to JavaScript object and call Object.values(). The result is an array of values.
var obj = JSON.parse(jsonData);
var result = Object.values(obj);
If you pass a function to JSON.parse, it will be called each time a value is parsed:
function get_values(json) {
let values = []
JSON.parse(json, (key,value)=>{ values.push(value) })
return values
}
ex:
get_values(`{"a":1, "b":[true, false], "c":3}`)
// returns a list of:
• 1
• true
• false
• [true, false]
• 3
• {a:1, b:[true, false], c:3}
Note: If you don't consider the full object to be a "value", just remove the last item.
I have an array of objects and an array of string and I am tying to combine the two in sequence meaning I would like to first item on the array to be stored only in the first object, second item of the array only in the second object, ect. Something like the following.
var objects = [ obj1, obj2, obj3];
var strings = ["123", "456", "789"];
//Result
var results = [
{
"obj1": {
number: "123"
},
{
"obj2": {
number: "456"
},
{
"obj2": {
number: "789"
}
];
I have been trying to do this with a push and a for loop but I seem to end up with each object containing all three strings.
Its easy:-
for (var i = 0; i < objects.length; i++) {// start loop for getting values one by one from object array
objects[i].number = strings[i]; // assign string values to object array values
}
Matched object and string share the same array index:
for (var i = 0; i < objects.length; i++) {
objects[i].number = strings[i];
}
Or you could do this using the map function:
var results = objects.map(function (value, index) {
return Object.assign({}, value, { number: strings[index] });
});
The other answers are good I just wanted to give you another way. This way you also do not modify the existing objects array
In case you don't know Object.assign add to the first argument (in our case the empty object {}) all the properties from the other object arguments. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Also, you can learn here about the map function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Can we convert an Object to a 2D Array,
My Object is like this
So That Array Key will be like 'STARS_2' and value is ["STARS_4", "STARS_0", "STARS_12"]
with My attempts I can get something like this,
With this Code,
var testArray =[];
_.map(childFieldNames, function (value, key) {
var newArray = new Array();
newArray[key] = value;
testArray.push(newArray);
});
Here Keys are actually another array, which I do not want. I want key should be like 'STARS_2' , i.e. property of master object.
Is this what you need?
var ary2D = Object.keys(childFieldNames).map(function (key) {
return childFieldNames[key];
});
better version for what Shilly showed would be:
const arr2D = Object.values(childFieldNames);
Object.entries(obj)
E.g.
const objVariable = {name: "Ted", job: "Dentist"}
const 2dArray = Object.entries(objVariable)
console.log(2dArray) // will print [["name", "Ted"], ["job", "Dentist"]]
Object.entries is a static method that belongs to the Object class. As a parameter, it accepts an object and returns a two-dimensional array.
Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
You don’t need to create your structure into 2D array to just iterate over each key and its respective value(which is an array). If you want to iterate over it you can do something like this.
const object = {
a: [1,2,3],
b: [2,3,5]
};
for (const [key, value] of Object.entries(object)) {
value.forEach(v=>{
console.log(`${key}: ${v}`);
})
}