简体   繁体   中英

Remove comma if its the last item in the object

I am trying to remove the comma on the item if its the last item on the object.

 Object.entries(product.name).map(
            ([key, value]) => {
            return value ? <span>{`${key}, `}</span> : value && key === key.length - 1 ? <span>{key}</span> : null;
            })

So basically, if the value of key is true, it will return a comma right beside the key & if its not the last, if its the last it must only return the key without the comma.

How can I achieve this here?

A better approach would be to filter the true values from product.name object and then simply join the array with comma ,

 const products = Object.keys(product.name).filter((key)=>product.name[key]);
 const commaSeperatedProducts = products.join(",")

You can check the index. If the index is equal to arr.length - 1 it's the last element in the array.

Object.entries(product.name).map(([key, value], index, arr) => {
  if (!value) return;
  return index === arr.length - 1 ? (
    <span>{key}</span>
  ) : (
    <span>{`${key}, `}</span>
  );
});

remove the "," from the return in the map, and add join to return it with comma. i do not have your data structure but something like that should do the work:

Object.entries(product.name).map(
   ([key, value]) => {
       return value ? <span>{`${key}`}</span> : value && key === key.length - 1 ? <span>{key}</span> : null;
    }).join(", ")

key === key.length - 1? this condition is incorrect. key.length -1 does not return the last Key. Use Object.keys(ObjName).length -1 to get the Number of last Key and then Use Object.keys(ObjName)[keyNumber] to get the last key.

var lastKeyNum = Object.keys(product.name).length -1
Object.entries(product.name).map(
    ([key, value]) => {
    return value ? key === Object.keys(product.name)[lastKeyNum] ? <span>{key}</span>  : <span>{`${key}, `}</span>  : null
})

It's unclear what the data structure product looks like, so I've made an assumption and included it with the answer I provided. However, if this assumption is wrong do update me.

In addition, each span you are mapping to needs a unique ID (key) so that they are used performantly.

import React from "react";
import ReactDOM from "react-dom";

const product = {
  name: {
    hat: "UID-001",
    shoes: "UID-002",
    jacket: "UID-003",
    jeans: "UID-004"
  }
};

const MapExample = () =>
  Object.entries(product.name).map(([key, _], idx, arr) =>
    idx === arr.length - 1 ? <span key={key}>{`${key}`}</span> : <span key={key}>{`${key},`}</span>
  );

ReactDOM.render(<MapExample />, document.getElementById("root"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM