I have object as var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}] . I want to get key and value this sample
PRODUCT_ID is P01
M01 is 1
M02 is 2
M03 is null
I try with as follow
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + " is " + obj[key]);
}
}
It't not working , it's show wrong with format.
0 is [
1 is {
2 is "
3 is P
4 is R
5 is O
6 is D
...etc
I using javascript to this. If maybe can convert to json and show this .
My guess is that the object you receive is a string not an actual object or array. This is why with your code, it gives the output.
To convert to an actual JS object use JSON.parse() and it will return an array as expected.
For instance,
const myArray = JSON.parse(obj);
myArray.forEach(x => Object.entries(x).map(([key, value]) => console.log(`${key} is ${value}\n`)))
Observation :
for...in statement iterates over the enumerable properties of an object. Hence, As per the code in OP :
var obj = [{
"PRODUCT_ID": "P01",
"M01": 1,
"M02": 2,
"M03": null
}];
for (var key in obj) {
console.log(key); // 0
}
Try this :
var obj = [{
"PRODUCT_ID": "P01",
"M01": 1,
"M02": 2,
"M03": null
}];
for (var i of obj) {
for (var j in Object.keys(i)) {
console.log(Object.keys(i)[j] + " is " + i[Object.keys(i)[j]]);
}
}
the problem is you are querying obj, while the actual obj is obj[0]. obj is an array with 1 element. try this
var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}];
for (var key in obj[0]) {
if (obj[0].hasOwnProperty(key)) {
console.log(key + " is " + obj[0][key]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
use Object.keys() method to access the keys in your object and then simply concatenate the key with its value.
this is not the most elegant solution, but it will help you understand.
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]' //string
obj = JSON.parse(obj);
console.log(Object.keys(obj[0])) //so that you can see what this does
obj.forEach(object => {
Object.keys(object).forEach(key => {
$("#values").append($("<p>"+key +" is "+ object[key]+"</p>"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
The thing here is that you are treating an array like an object. Change your code for:
for(x=0;x <obj.length;x++){
// Here you have each object of your array.
var json = obj[x];
var arrayOfKeys = Object.keys (json);
//other code.
}
See Object.entries(), Array.prototype.map(), and Template Literals for more info.
// Input.
const input = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
// Output.
input.map(x => Object.entries(x).map(([key, value]) => console.log(`${key} is ${value}\n`)))
You can use Object.entries() like:
const jsonString = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]'
// parse your json string first
const arr = JSON.parse( jsonString );
// Get the object from the array
const obj = arr[0] || {};
for (const [key, value] of Object.entries(obj)) {
console.log(key + ' is '+value);
}
Your code almost correct. But as you have data array not object you need to loop trough the object to achieve desire output.
Guessing OP has:
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]';
for (var key in obj) {
console.log(key + " is " + obj[key]);
}
//var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]';
obj = JSON.parse(obj);
for (var key in obj) {
for (var k in obj[key]){
console.log(k + " is " + obj[key][k]);
}
}
Alternative:
//var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
var obj = '[{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]';
obj = JSON.parse(obj);
obj.map(e => Object.entries(e).map(([k, v]) => console.log(k, "is", v)))
Related
I have an object that contains key pair values of objects that are in array form:
let obj = {};
let joinedData;
obj["key1"] = ["val1", "val2"];
obj["key2"] = ["val3", "val4"];
I want to join all the values together as a string:
for (const [key, values] of Object.entries(obj)) {
joinedData = `${values.join(",")}`;
}
The expected result is "val1,val2,val3,val4"
But joinedData is empty.
I suspect that it's because the values are objects and not array (when I use typeof).
How to get the expected result in this case?
You can use Object.values and flat:
let obj = { key1: ["val1", "val2"], key2: ["val3", "val4"] };
let joinedData = Object.values(obj).flat().join();
console.log(joinedData);
If you have some arrays that contain empty strings, then you may want to filter those out, with filter(Boolean):
let obj = { key1: ["val1", "val2"], key2: ["val3", "val4"], key3: [""], key4: [""] };
let joinedData = Object.values(obj).flat().filter(Boolean).join();
console.log(joinedData);
You can use this - joinedData = Object.values(obj).flat().join(',')
First join the both list in any single list like
var newlist = obj["key1"].join(obj["key2"]);
After join the values by comma seprated
joinedData = newlist.join(',');
get all values from obj using let objValues = Object.values(obj);
now you can a for loop over obj values and append both elms like for(const v of objValues) { joinedData.push(v[0]); joinedData.push(v[1]); } or nested for loop works too
let obj = {};
let joinedData = [];
obj["key1"] = ["val1", "val2"];
obj["key2"] = ["val3", "val4"];
let objValues = Object.values(obj); //List of tuples ?
for (const v of objValues) {
joinedData += v[0] + ',';
joinedData += v[1] + ' ';
}
console.log(joinedData)
if you were to write out your object literally, you would have:
obj = {key1 : ["val1", "val2"], key2 : ["val3", "val4"]}
Array.join() concatenates array elements into a string. Array elements that are arrays themselves cannot be directly concatenated into a string. Try:
let str = '';
for(let i of Object.values(obj)) { // retrieve each value (which is an array)
str += i.join(', ') + ', '; // join elements of each array & concatenate
} // extra comma between each joined array
console.log(str)
You still need to strip the extra comma off the end
Complete a function that takes in three parameters, an object, and a string (which will represent a key), and a value. The function needs to add a property to the inputted object. The property's key is a string, and the value of this property should be the inputted value. The function should return the inputted object.
function addProperty(obj, key, value) {
// your code here
var obj = {};
obj[key] = value;
return obj;
}
As this function stands it takes in one key and one value. I need it to let me add as many keys and values as I want. Please help.
1) Passing array of key and value
function addProperty(obj, keyArr, valueArr) {
keyArr.forEach((k, i) => {
obj[k] = valueArr[i];
});
return obj;
}
const keys = ["A", "B", "C"];
const values = ["value of A", "value of A", "value of A"];
let obj = {};
obj = addProperty(obj, keys, values);
console.log(obj);
2) Iterating over array key and calling the function as many times as length of the key array
function addProperty(obj, key, value) {
obj[key] = value;
return obj;
}
const keys = ["A", "B", "C"];
const values = ["value of A", "value of A", "value of A"];
let obj = {};
keys.forEach((k, i) => {
obj = addProperty(obj, k, values[i]);
});
console.log(obj);
try this
function addProperty(obj, keys_and_values) {
// your code here
var obj = {}
for (let key in keys_and_values) {
obj[key] = keys_and_values[key]
}
return obj
}
console.log(addProperty({}, {"name": "hi", "age": 69}))
output
{
age: 69,
name: "hi"
}
You'll have to remove var obj = {} in your addProperty function. I think you want to pass the object which should be expanded, right?
var obj = {};
var data = [{
key: "KEYA",
value: "VALUEA"
},
{
key: "KEYB",
value: "VALUEB"
}
];
var data2 = [{
key: "KEYC",
value: "VALUEC"
}
];
//Add key/value pairs to obj
console.log(addProperty(obj, data));
//Add another key/value pair to obj
console.log(addProperty(obj, data2));
function addProperty(obj, data) {
for (var key in data) {
obj[data[key].key] = data[key].value;
}
return obj;
}
I don't know why everyone were over explaining the question here-
We need to achieve 3 things here-
Function needs to add a property to the inputted object.
The value of property should be the inputted value.
function should return the inputted object.
function addProperty(obj, key, value) {
obj[key] = value ;
return obj ;
}
How to assign the value to array in object value? It may has multiple input coming in and expected the input appended to array.
Code:
var ob = {};
$.each( input, function( key, value ) {
var v = [];
ob[key] = v.push(value);
console.log( v );
console.log( "obj: " + ob );
console.log( key + ": " + value );
});
Input:
First input- {A: "34",B: "2"}
Second input- {A: "21",B: "11"}
Expected:
ob = {A: ["34","21"] ,B: ["2","11"]}
Hope this helps,
var ob = {};
$.each(input, function(key, value) {
if (!ob[key]) {
ob[key] = []; // Creates a new Array for the key, if no array is there
}
ob[key].push(value); // Pushes the value to the array of the particular key
});
Create a function and an object variable. Check if the key exist in that object. If it does not exist they create the key and push the values
let input1 = {
A: "34",
B: "2"
}
let input2 = {
A: "21",
B: "11"
}
// a object which will hold the key and value
let finalObj = {};
// create a function which will be called o add key an value property to object
function createObj(obj) {
// iterate the object
for (let keys in obj) {
// check if final object has the relevent key
if (finalObj.hasOwnProperty(keys)) {
// if it has that key then push the value according to the key
finalObj[keys].push(obj[keys])
} else {
finalObj[keys] = [obj[keys]]
}
}
}
createObj(input1)
createObj(input2)
console.log(finalObj)
The problem is v empties on each iteration, because of this line:
var v = [];
Try doing this instead:
$.each(input, (key, val) => {
if (ob[key]) {
ob[key].push(val);
} else {
ob[key] = [val];
}
});
By looking at the "Array" image, how can I access all levels of this array?
I tried doing a foreach but this only allows me to access to the first object, I can't acces the second object filled with strings.
for (var key in result)
{
if (result.hasOwnProperty(key))
{
console.log(key, result[key]);
for(var item in result[key])
{
console.log(item);
}
}
}
I also tried:
result[key[item]]
But it appears to be undifined.
I know it's easy to access all elements by the name, but the names change constantly, so the solution should be dynamic.
I added the Demo on the comments to see behavior.
Object.keys(obj) returns an array of the keys in obj.
var obj = {
a: 1,
b: 2,
m: 3,
x: 4,
y: 5,
z: 6
}
//get all the keys in an array:
var keys = Object.keys(obj)
console.log("keys: " + keys);
//iterate through the object by its keys:
for (var i = 0; i < keys.length; i++){
console.log("key " + keys[i] + " has value " + obj[keys[i]]);
}
Update based on your comment
I think you're asking to apply this solution to an arbitrary-depth object. My solution would be to wrap the previous trick in a function and call it recursively if there are nested objects:
var obj = {
a: {foo:"bar",foof:"barf"},
b: 2,
m: 3,
x: {baz:{really:{more:{objects: "yeah, there could be a lot"}}}},
y: 5,
z: 6
}
function getKeysDeep(obj,prefix){
//get all the keys in an array:
var keys = Object.keys(obj)
//console.log(prefix + "keys: " + keys);
//iterate through the object by its keys:
for (var i = 0; i < keys.length; i++){
if (obj[keys[i]] !== null && typeof obj[keys[i]] === 'object') {
console.log("key " + keys[i] + "'s value is an object");
getKeysDeep(obj[keys[i]],prefix + keys[i] + ": ");
} else {
console.log(prefix + "key " + keys[i] + " has value " + obj[keys[i]]);
}
}
}
getKeysDeep(obj,"")
This loop worked too!
Object.keys(result).forEach(function (key) {
console.log(result[key]);
var test = result[key];
Object.keys(test).forEach(function (key) {
console.log(test[key]);
var testTwo = test[key];
Object.keys(testTwo).forEach(function (key) {
console.log(testTwo[key]);
var testThree = testTwo[key];
});
});
});
But #nvioli answer is more accurate.
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]);
}