0

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 .

4
  • 3
    Seems obj is string, Can you share the output of typeof obj ? Commented Apr 3, 2018 at 12:27
  • Oh, Do you have idea for this ? Commented Apr 3, 2018 at 12:29
  • 1
    It's array of objects with one object in it. delete "[ ]" and try again. Commented Apr 3, 2018 at 12:30
  • @BrianCrist I added answer, hope it will work as per your expectation. Thanks Commented Apr 4, 2018 at 5:43

8 Answers 8

2

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`)))
Sign up to request clarification or add additional context in comments.

Comments

1

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]]);
  }
}

Comments

1

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>

12 Comments

That's right. If you could change your obj definition to: obj = {"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}, it'll be more readable
It is quite clear, that OP has not an object, please read the question.
@Teemu, it is quite clear that is exactly what I meant by the actual obj is obj[0]
Read the question, take a careful look over the provided output, what you see?
@BrianCrist, please show the error or some relevant feedback, since it is working in the snippet, I cannot tell what the problem is, do you happen to have more than 1 element in your array obj in your real scenarios?
|
1

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>

4 Comments

Sorry , I get with ["0"]
I understand that he has an array of object/s and the answer attends to that
maybe he edited the question to make it an array? even so, i will attend to that too.
@Teemu see snippet for string.
0

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.
 }

Comments

0

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`)))

6 Comments

It is quite clear, that OP has not an object, please read the question.
"I have object" @Teemu
That's what they think, look at the output.
@Teemu i think we should change to json or array . Do you think so ?
@BrianCrist At first you've to do JSON.parse to parse your string to an object, then follow some of these answers.
|
0

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

1 Comment

@BrianCrist Please try to use JSON.parse first to get actual array from the JSON string like show in the demo above.
0

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

8 Comments

Your code is almost correct, except it doesn't solve the problem OP is facing. Don't you guys read the questions anymore? Almost all the answers on this post are somewhat useless for OP, including this ...
@Teemu what OP wants? How to get key and value of object in javascript?
Yep, but the gotcha is, that they don't have an object ... Like I said, don't you guys read the questions anymore?
what do you mean they don't have an object? Op clearly said I have object as var obj = [{"PRODUCT_ID":"P01","M01":1,"M02":2, "M03": null}]
Please read the entire question! The output of the provided for ..in loop would totally be different from what OP says they're getting, if they had an object ...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.